汇总数据

时间:2016-01-08 11:52:36

标签: sql sql-server sql-server-2012

我正在尝试将基本查询中的所有数据汇总到2列,避免使用空值。

第1列显示文件编号,下一列显示1,2 ... 12,以显示加入文件编号的次数,因为每个连接代表链接数。

请帮忙。查询如下。

with base as
(select FileNumber as 1
       ,p3.FileNumber as 2
       ,p4.FileNumber as 3
       ,p5.FileNumber as 4
       ,p6.FileNumber as 5
       ,p7.FileNumber as 6

from pricing_advances p1 
left outer join pricing_advances p2  on coalesce([To File Number],reinstatedTo) = FileNumber 
left outer join pricing_advances p3 on coalesce([To File Number],reinstatedTo) = p3.FileNumber 
left outer join pricing_advances p4 on coalesce(p3.[To File Number],p3.reinstatedTo) = p4.FileNumber 
left outer join pricing_advances p5 on coalesce(p4.[To File Number],p4.reinstatedTo) = p5.FileNumber 
left outer join pricing_advances p6 on coalesce(p5.[To File Number],p5.reinstatedTo) = p6.FileNumber )
select * from base

1 个答案:

答案 0 :(得分:0)

您的数据结构非常糟糕。您应该将它们存储在一个单独的表中,而不是将值存储在列中,每个FileNumber只有一行。

假设FROM子句正确,您可以使用COALESCE()获得第一场比赛:

select COALESCE(p1.FileNumber, p2.FileNumber, p3.FileNumber, . . .
               ) as FileNumber

如果需要匹配列表,请改用字符串连接。假设FileNumber是一个字符串:

select stuff( (coalesce(',' + p1.FileNumber, '') +
               coalesce(',' + p2.FileNumber, '') +
               coalesce(',' + p3.FileNumber, '')
               . . .
              ), 1, 1, '')