如何解决SQL Server 2016中的数据透视表
我在旋转SQL Server 2016中的表时遇到问题。请考虑以下数据/查询
WITH DATA1 AS
(
SELECT 123 cid,'test' cname,'2020-03-17' dt,'BELLE' fc,3782703 mn union all
SELECT 123 cid,'2020-03-12' dt,'WOO' fc,25679 mn union all
SELECT 345 cid,'test2' cname,'2019-03-17' dt,'king' fc,3782703 mn union all
SELECT 345 cid,'2019-03-12' dt,'east' fc,25679 mn union all
SELECT 111 cid,'test3' cname,'2019-02-12' dt,2 mn
)
select *
from DATA1
PIVOT (
MAX(mn) FOR fc IN (
[BELLE],[WOO],[KING],[EAST]
)
) a
我正在尝试将dt和mn用作fc中的值。所以基本上我正在寻找此输出。
cid cname fc1_dt fc1_name fc1_mn fc2_name fc2_dt fc2_mn
123 test 2020-03-17 BELLE 3782703 woo 2020-03-12 25679
345 test2 2019-03-17 king 37 east 2019-03-12 25
111 test3 2019-02-12 east 2
我试图像这样添加到max
函数中,但是它不起作用
PIVOT (
MAX(mn),max(dt) FOR fc IN (
[BELLE],[EAST]
)
) a
有人可以帮我修改查询以产生上面的输出吗?
解决方法
一个选项使用row_number()
和条件聚合。假设您想要第一列中的最新日期:
select cid,cname,max(case when rn = 1 then dt end) fc1_dt,max(case when rn = 1 then fc end) fc1_name,max(case when rn = 1 then mn end) fc1_mn,max(case when rn = 2 then dt end) fc2_dt,max(case when rn = 2 then fc end) fc2_name,max(case when rn = 2 then mn end) fc2_mn
from (
select d.*,row_number() over(partition by cid,cname order by dt desc) rn
from data1 d
) d
group by cid,cname
如果每个组要处理2行以上,则需要使用更多条件表达式来扩展select
子句。
cid | cname | fc1_dt | fc1_name | fc1_mn | fc2_dt | fc2_name | fc2_mn --: | :---- | :--------- | :------- | ------: | :--------- | :------- | -----: 123 | test | 2020-03-17 | BELLE | 3782703 | 2020-03-12 | WOO | 25679 345 | test2 | 2019-03-17 | king | 3782703 | 2019-03-12 | east | 25679 111 | test3 | 2019-02-12 | east | 2 | null | null | null
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。