sql:如何创建第三列并移动具有相同 ID 的 2° 结果
sql: how create third column and move 2° result with same id
我有这种情况
id
name
barcode
123
aaa
123123
123
aaa
231233233312
444
bbb
1238882
444
bbb
43434344
555
ccc
4543443
453
ddd
123
我希望将具有相同 ID 的第二个结果移动到第三列:
id
name
barcode1
barcode2
123
aaa
123123
231233233312
444
bbb
1238882
43434344
555
ccc
4543443
empty
453
ddd
123
empty
有人可以帮我吗?
为了使您的问题有意义,您需要一个定义行顺序的列。让我假设你有这样的行,叫做 ordering_id
.
然后,可以使用window函数枚举每组的行数,条件聚合进行透视:
select id, name,
max(case when rn = 1 then barcode end) as barcode1,
max(case when rn = 2 then barcode end) as barcode2
from (
select t.*,
row_number() over(partition by id, name order by ordering_id) rn
from mytable t
) t
group by id, name
您可以将 group by
与 count
、min
和 max
聚合函数一起使用,如下所示:
Select id, name,
Min(barcode) as barcode_1,
Case when count(1) > 1 then max(barcode) end as barcode_2
From your_table
Group by id, name
我有这种情况
id | name | barcode |
---|---|---|
123 | aaa | 123123 |
123 | aaa | 231233233312 |
444 | bbb | 1238882 |
444 | bbb | 43434344 |
555 | ccc | 4543443 |
453 | ddd | 123 |
我希望将具有相同 ID 的第二个结果移动到第三列:
id | name | barcode1 | barcode2 |
---|---|---|---|
123 | aaa | 123123 | 231233233312 |
444 | bbb | 1238882 | 43434344 |
555 | ccc | 4543443 | empty |
453 | ddd | 123 | empty |
有人可以帮我吗?
为了使您的问题有意义,您需要一个定义行顺序的列。让我假设你有这样的行,叫做 ordering_id
.
然后,可以使用window函数枚举每组的行数,条件聚合进行透视:
select id, name,
max(case when rn = 1 then barcode end) as barcode1,
max(case when rn = 2 then barcode end) as barcode2
from (
select t.*,
row_number() over(partition by id, name order by ordering_id) rn
from mytable t
) t
group by id, name
您可以将 group by
与 count
、min
和 max
聚合函数一起使用,如下所示:
Select id, name,
Min(barcode) as barcode_1,
Case when count(1) > 1 then max(barcode) end as barcode_2
From your_table
Group by id, name