SQL Server 使用 case 语句进行数据透视

2022-01-22 00:00:00 pivot 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

可以将我的案例陈述合并到一个支点中来实现这一点吗?谢谢

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 

相关文章