我有一个数据库,其中包含以下各行:
ID | Date start | Date end ---------------------------------- a | 01-01-1950 | 30-01-1951 a | 01-01-1948 | 31-12-1949 a | 31-01-1951 | 01-06-2000 b | 01-01-1980 | 01-08-2010 c | 01-01-1990 | 31-12-2017 c | 31-01-1985 | 31-12-1989
我得到了什么
选择要返回以下内容的查询:
ID | Date start 1 | Date end 1 | Date start 2 | Date end 2 | Date start 3 | Date end 3 --------------------------------------------------------------------------------------------------- a | 01-01-1948 | 31-12-1949 | 01-01-1950 | 30-01-1951 | 31-01-1951 | 01-06-2000 b | 01-01-1980 | 01-08-2010 c | 31-01-1985 | 31-12-1989 | 01-01-1990 | 31-12-2017
我想要的是:
我能够找到的大多数东西都希望在同一列中进行,或者不希望按时间顺序进行排序,因此不幸的是,这些情况不适用于我。
我现在真的知道如何解决这个问题。
如果只有三个日期,则pivot/ conditional合计应该可以:
pivot
select id, max(case when seqnum = 1 then dstart end) as start_1, max(case when seqnum = 1 then dend end) as end_1, max(case when seqnum = 2 then dstart end) as start_2, max(case when seqnum = 2 then dend end) as end_2, max(case when seqnum = 3 then dstart end) as start_3, max(case when seqnum = 3 then dend end) as end_3 from (select t.*, row_number() over (partition by id order by dstart) as seqnum from t ) t group by id;
注意:您必须指定输出中的列数。如果您不知道有多少个,可以: