带有固定行的SQL Sum表?

时间:2014-05-29 11:02:50

标签: sql sql-server count sum

我有一个查询,我想给一个固定的表输出(所以我可以更容易在Excel中绘图)。 查询如下:

SELECT 

Case

WHEN ScrapsReasonID = 2339 THEN 'Box 5'

WHEN ScrapsReasonID = 2340 THEN 'Box 6'

WHEN ScrapsReasonID = 2342 THEN 'Box 7'

WHEN ScrapsReasonID = 2343 THEN 'Box 8'

WHEN ScrapsReasonID = 2344 THEN 'Box 9'

Else 'Unknown'

END 

AS 'BoxNumber',

count(Case When PartNumberID = '378' Then Scraps End) AS '9.5mm',

count(Case When PartNumberID = '379' Then Scraps End) AS '10.0mm',

count(Case When PartNumberID = '380' Then Scraps End) AS '10.5mm'


FROM [ProcessControl].[dbo].[OutputScrap]

WHERE 

MachineId = '93'

And ScrapsReasonID In

(
'2339',
'2340',
'2342',
'2343',
'2344'
)

And PDate Between '22-may-2014' and '29-may-2014'

GROUP BY ScrapsReasonID

如果在设置日期之间肯定存在所有5个scrapreasonID,则此方法有效,但如果仅有3例,则Sum表中只有3行。有没有办法总是返回所有5个scrapreasonID和9.5,10.0,10.5的零值,如果它们不存在?

1 个答案:

答案 0 :(得分:1)

您想使用left outer join而不是case语句。另外,我做了以下更改:

  • count()更改为sum()。想要在名为`scraps的字段中对值进行求和似乎更合理,尽管我可能错了。
  • 在条件聚合中添加了Else 0。我假设您在没有匹配而不是0时想要NULL
  • 删除了ScrapsReasonID上的条件。 join会进行必要的过滤。
  • 将剩余条件移至on子句,因此where不会将外部联接转换为内部联接。
  • 删除了列名的单引号。对于SQL Server,使用方括号(我假设SQL Server是因为三部分表命名约定)。
  • 将日期格式更改为ISO标准YYYY-MM-DD格式。

以下是生成的查询

SELECT bn.BoxNumber,
       SUM(Case When PartNumberID = '378' Then Scraps Else 0 End) AS [9.5mm],
       SUM(Case When PartNumberID = '379' Then Scraps Else 0 End) AS [10.0mm],
       SUM(Case When PartNumberID = '380' Then Scraps Else 0 End) AS [10.5mm]
FROM (SELECT 2339 as ScrapsReasonID, 'Box 5' as BoxNumber UNION ALL
      SELECT 2340, 'Box 6' UNION ALL
      SELECT 2342, 'Box 7' UNION ALL
      SELECT 2343, 'Box 8' UNION ALL
      SELECT 2344, 'Box 9' 
     ) bn LEFT OUTER JOIN
     [ProcessControl].[dbo].[OutputScrap] os
     ON os.ScrapsReasonID = bn.ScrapsReasonID AND
        os.MachineId = '93' AND
        os.PDate Between '2014-05-22' and '2014-05-29'
GROUP BY bn.BoxNumber;