SQL Server pivot using case statement(SQL Server 使用 case 语句进行数据透视)
问题描述
我正在尝试转出一些数据,我想我需要在我的转码代码中加入一个 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
这篇关于SQL Server 使用 case 语句进行数据透视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server 使用 case 语句进行数据透视
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 无法解决整理冲突 2021-01-01
