0

我有一个这样的 SQL Server 表

ID    amount        type
1         10        material
1          5        spare parts
1          5        material

我需要进行查询并获得这样的输出

ID        material        spare parts
1            15                     5


但是我有太多的 IDS 和类型,所以我需要动态添加项目,无论它们的数量是多少。

4

1 回答 1

3

您正在寻找一个动态的支点。基本上,这可以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

DB Fiddle 上的演示

于 2020-04-01T14:27:40.080 回答