我建议您使用row_number()
条件聚合来执行此操作:
select t.animal,
max(case when seqnum = 1 then livein end) as Column1,
max(case when seqnum = 2 then livein end) as Column2
from (select t.*, row_number() over (partition by animal order by (select NULL)) as seqnum
from t
) t
group by t.animal;
请注意,您无法表达数据中列的顺序——SQL 表本质上是无序的。以上选择任意排序。如果您有id
orCreatedAt
列,则可以使用它来指定顺序。
鉴于没有排序,以下也做了等效的工作:
select t.animal, min(t.LiveIn) as Column1,
(case when min(t.LiveIn) <> max(t.LiveIn) then max(t.LiveIn) end) as Column2
from t
group by t.animal;
编辑:
SQL 查询必须返回固定数量的列。 您不能让查询有时返回三列,有时返回四列。但是,您可以调整查询以返回更多列,通常可能是NULL
:
select t.animal, count(*) as NumLiveIn,
max(case when seqnum = 1 then livein end) as Column1,
max(case when seqnum = 2 then livein end) as Column2,
max(case when seqnum = 3 then livein end) as Column3,
max(case when seqnum = 4 then livein end) as Column4
from (select t.*, row_number() over (partition by animal order by (select NULL)) as seqnum
from t
) t
group by t.animal;
在这种情况下,我还将添加一个环境数量列。