sql - 从 SQL Server 中的一列数据创建列
问题描述
我有一个这样的 SQL Server 表
ID amount type
1 10 material
1 5 spare parts
1 5 material
我需要进行查询并获得这样的输出
ID material spare parts
1 15 5
但是我有太多的 IDS 和类型,所以我需要动态添加项目,无论它们的数量是多少。
解决方案
您正在寻找一个动态的支点。基本上,这可以type
从表中选择 s 列表,然后根据该信息构建查询。然后,您可以使用 执行查询sp_executesql
。
对于您的表结构:
declare @sql nvarchar(max);
select @sql = string_agg(
'sum(case when type = ''' + type + ''' then amount else 0 end) [' + type + ']',
', ')
from (select distinct type from mytable) t;
set @sql = N'select id, ' + @sql + ' from mytable group by id';
select @sql; -- debug
-- exec sp_executesql @sql; -- execute for real
对于您的示例数据,这会生成以下查询(为了便于阅读,我添加了换行符):
select
id,
sum(case when type = 'material' then amount else 0 end) [material],
sum(case when type = 'spare parts' then amount else 0 end) [spare parts]
from mytable
group by id
执行后,你得到结果:
编号 | 材料 | 备件 -: | --------: | ----------: 1 | 15 | 5
推荐阅读
- firebase - 试图在个人资料视图SwiftUI上显示获取的firebase数据
- python - 如何从邻接列表构建嵌套树结构?
- jupyter-notebook - 如何在 PyCharm 中编辑 Jupyter Notebook 元数据?
- html - ios 的 slick 解决方法
- python - 如何使用 z3py 设置“最多 n 次”等要求?
- python - 使用pyaudio的回调模式使用pydub播放音频时出现问题
- php - 如何在 php 文件中包含静态资源,如图像、css 和 javascript
- sql - 针对 dbms 问题改进 sql 查询
- firebase - Firebase 事件发生时更新反应原生(博览会)UI
- python - 如何仅打印此输出的最后一行?