带有MIN()和多列的SQL PIVOT表

时间:2018-11-15 17:17:14

标签: sql sql-server sql-server-2008-r2

这是表结构

ID          TypeX   TypeXDesc           XDate       TypeCodeY
040001      3669    Unspecified Cat    2005-08-08   1
040001      3669    Unspecified Cat    2006-08-29   2
040001      37515   Tear Film          2005-08-08   1
040001      37999   Disor              2004-07-22   1

使用PIVOT将表上方转换为INTO

ID          TypeX_1 TypeXDesc_1         XDate_1     TypeCodeY_1     TypeX_2 TypeXDesc_2         XDate_2     TypeCodeY_2     TypeX_3 TypeXDesc_3 XDate_3     TypeCodeY_3
040001      3669    Unspecified Cat    2005-08-08   1               37515   Tear Film          2005-08-08   1               37999   Disor       2004-07-22  1

看看相同的TypeX代码,但XDate不同,我们需要获取Min(XDate),因此第一行的条件不是第二行。

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合来完成此操作。在这种情况下,您可以使用typex枚举id / row_number()组内的行。您可以使用typexid / dense_rank()来枚举组。

然后,使用条件聚合:

select t.id,
       max(case when grpnum = 1 and seqnum = 1 then typex end) as typex_1,
       max(case when grpnum = 1 and seqnum = 1 then TypeXDesc end) as TypeXDesc_1,
       max(case when grpnum = 1 and seqnum = 1 then XDate end) as XDate_1,
       max(case when grpnum = 1 and seqnum = 1 then TypeCodeY end) as TypeCodeY_1,
       max(case when grpnum = 2 and seqnum = 1 then typex end) as typex_12,
       max(case when grpnum = 2 and seqnum = 1 then TypeXDesc end) as TypeXDesc_2,
       max(case when grpnum = 2 and seqnum = 1 then XDate end) as XDate_2,
       max(case when grpnum = 2 and seqnum = 1 then TypeCodeY end) as TypeCodeY_3,
       max(case when grpnum = 3 and seqnum = 1 then typex end) as typex_1,
       max(case when grpnum = 3 and seqnum = 1 then TypeXDesc end) as TypeXDesc_3,
       max(case when grpnum = 3 and seqnum = 1 then XDate end) as XDate_3,
       max(case when grpnum = 3 and seqnum = 1 then TypeCodeY end) as TypeCodeY_3
from (select t.*,
             row_number() over (partition by id, typex order by xdate as seqnum,
             dense_rank() over (partition by id order by typex) as grpnum
     from t
    ) t
group by id;