我可以从以下位置更改选择记录的显示方式吗
Ticket Colour
12321 Green
12321 Blue
12321 Yellow
22653 Red
22653 Black
收件人:
Ticket Colour1 Colour2 Colour3
12321 Green Blue Yellow
22653 Red Black
答案 0 :(得分:3)
我建议在这里使用LISTAGG
SELECT
Ticket,
LISTAGG(Colour, ',') WITHIN GROUP (ORDER BY Colour) AS Colours
FROM yourTable
GROUP BY Ticket;
Ticket Colours
12321 Blue,Green,Yellow
22653 Black,Red
我建议这样做的原因是,也许您的数据集最终可能会超过3列。动态SQL可能会帮助您解决此问题,但这将需要大量工作。
答案 1 :(得分:2)
如果需要多个列,则可以使用条件聚合:
select ticket,
max(case when seqnum = 1 then colour end) as colour_1,
max(case when seqnum = 2 then colour end) as colour_2,
max(case when seqnum = 3 then colour end) as colour_3
from (select t.*,
row_number() over (partition by ticket order by ticket) as seqnum
from t
) t
group by ticket;
我应该注意,不能保证颜色的顺序。 SQL表表示 unordered 集,因此除非有另一列指定排序,否则不进行排序。
答案 2 :(得分:0)
create table ex(
no number,
colour varchar(20));
insert into ex values(12321, 'Green');
insert into ex values(12321 , 'Blue');
insert into ex values(12321 , 'Yellow');
insert into ex values(22653 , 'Red');
insert into ex values(22653 , 'Black');
select * from ex;
SELECT LISTAGG(colour, ', ') WITHIN GROUP (ORDER BY no)
FROM ex group by no;
输出
12321 Blue, Green, Yellow
22653 Black, Red