繁体   English   中英

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

[英]SQL PIVOT table with MIN() and on Multiple columns

这是表格结构

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将上表转换成下表

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),因此第一行是合格的,而不是第二行。

您可以使用条件聚合来完成此操作。 在这种情况下,可以使用row_number()枚举typex / id组内的行。 您可以枚举组, typex / id使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM