首页 > 解决方案 > 组合多条记录以输出单个结果

问题描述

我正在搜索零件表,并希望按公司编号将数据结果分成几列。每条记录都使用公司编号和零件编号以及其他一些关键字段来使它们独一无二。我想找到零件号并用所有公司编号作为列填充一行。如果零件在公司中找到,则匹配的列和行填充为 1 或 true,否则为 0 或 null。

这是我的 SQL 语句:

SELECT PartNumber,CompanyNumber FROM DB.PartsTable PartsTable
WHERE PartNumber = &findPartNumber AND status= '1' 

这显示了我所拥有的以及我想要得到的结果:

预期产出

标签: sqlpivot

解决方案


Below would be the query -

select
sum(case when col#=601 then 1 else 0 end) as 601 ,
sum(case when col#=603 then 1 else 0 end) as 603,
sum(case when col#=605 then 1 else 0 end) as 605,
sum(case when col#=608 then 1 else 0 end) as 608,
sum(case when col#=612 then 1 else 0 end) as 612,
sum(case when col#=600 then 1 else 0 end) as 600
from <tableName> group by partNumber;

推荐阅读