我有一个查询,我想给一个固定的表输出(所以我可以更容易在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的零值,如果它们不存在?
答案 0 :(得分:1)
您想使用left outer join
而不是case
语句。另外,我做了以下更改:
count()
更改为sum()
。想要在名为`scraps的字段中对值进行求和似乎更合理,尽管我可能错了。Else 0
。我假设您在没有匹配而不是0
时想要NULL
。join
会进行必要的过滤。on
子句,因此where
不会将外部联接转换为内部联接。以下是生成的查询
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;