SQL Server枢轴使用案例语句 [英] SQL Server pivot using case statement
本文介绍了SQL Server枢轴使用案例语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试提取一些数据,我想我需要在我的透视代码中合并一个case语句,但是我不确定该如何做.我有下表:
I'm trying to pivot out some data and I think I need to incorporate a case statement in my pivot code but I'm not sure how. I have the table below:
ID AreaCode
1001 1501
1001 1502
1001 2301
1031 1010
1031 3012
1048 2304
1048 3012
1048 4022
每个AreaCode的第一位数字代表一个身体区域,我使用下面的代码表示受影响的身体区域:
The first digit of each AreaCode refers to a body area, I'm using the code below to indicate which body area is affected:
select id,
case when left(areaID,1)=1 then 'Yes' end Head,
case when left(areaID,1)=2 then 'Yes' end Face,
case when left(areaID,1)=3 then 'Yes' end Neck,
case when left(areaID,1)=4 then 'Yes' end Abdo
from #testcase
哪些给了我以下内容:
id Head Face Neck Abdo
1001 Yes NULL NULL NULL
1001 Yes NULL NULL NULL
1001 NULL Yes NULL NULL
1031 Yes NULL NULL NULL
1031 NULL NULL Yes NULL
1048 NULL Yes NULL NULL
1048 NULL NULL Yes NULL
1048 NULL NULL NULL Yes
但是,我需要我的输出表为每个id包含一行,就像这样:
However, I need my output table to contain one row for each id, like so:
id Head Face Neck Abdo
1001 Yes Yes Null Null
1031 Yes Null Yes Null
1048 Null Yes Yes Yes
能否将我的case语句合并到一个枢轴中以实现此目的?谢谢
Can incorporate my case statement in a pivot to achieve this? Thanks
推荐答案
您需要在case
语句的顶部使用aggregate
You need to use aggregate
on top of case
statements
SELECT id,
Max(CASE
WHEN LEFT(areaID, 1) = 1 THEN 'Yes'
END) Head,
Max(CASE
WHEN LEFT(areaID, 1) = 2 THEN 'Yes'
END) Face,
Max(CASE
WHEN LEFT(areaID, 1) = 3 THEN 'Yes'
END) Neck,
Max(CASE
WHEN LEFT(areaID, 1) = 4 THEN 'Yes'
END) Abdo
FROM #testcase
GROUP BY id
这篇关于SQL Server枢轴使用案例语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文