我有这种情况
id | 名称 | 条形码 |
---|---|---|
123 | aaa | 1123 |
123 | aaa | 231233233312 |
444 | bbb | 1238882 |
444 | bbb | 43434344 |
555 | ccc | 4543443 |
453 | ddd | 123 |
您可以将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
为了让您的问题有意义,您需要一个定义行顺序的列。让我假设您有这样一行,它被称为ordering_id
。
然后,您可以使用窗口函数来枚举每组的行,并使用条件聚合来透视:
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