我看过多篇与我的问题类似的帖子,但似乎都没有解决我的问题。
即使他们对该供应商的价值为零,我也试图将所有月份都记录下来。正如其他帖子中所建议的那样,我创建了另一个包含所有月份和年份数的表(实际上是视图)。然后在该视图上使用LEFT JOIN来尝试获取所有月份。
我还从另一篇文章中了解到将我的WHERE条件移动到连接ON条件。仍然没有快乐。
这是我的查询,但我没有收到每个供应商的所有12个月,只收到那个月有记录的供应商。
SELECT
Supplier, [Supplier Name],
m.[MonthNum Received] AS MonthNum,
m.[Year Received] AS [Year],
COUNT(OTD) AS [All], SUM(CASE WHEN s.OTD = 'Early' THEN 1 ELSE 0 END) AS Early,
SUM(CASE WHEN s.OTD = 'Ontime' THEN 1 ELSE 0 END) AS OnTime,
SUM(CASE WHEN s.OTD = 'Late' THEN 1 ELSE 0 END) AS Late,
SUM([Receipt Quantity]) AS Qty,
CAST(100 - CAST(SUM(CASE WHEN s.OTD = 'Late' THEN 1 WHEN s.OTD = 'Early' THEN 1 ELSE 0 END) AS DECIMAL(18, 0)) / COUNT(OTD) * 100 AS DECIMAL(18, 0)) AS [Percent]
FROM
[v_DA006-RECEIPTS_Months] m
LEFT JOIN
dbo.[v_DA006-RECEIPTS] AS s ON m.[MonthNum Received] = s.[MonthNum Received]
AND m.[Year Received] = s.[Year Received]
AND (s.[Receipt Quantity] <> 0)
GROUP BY
Supplier, [Supplier Name], m.[MonthNum Received], m.[Year Received]
答案 0 :(得分:0)
首先,您需要供应商。如果没有供应商表,您应该从交易中提取它们,然后加入您想要报告的月份,最后加入交易。
SELECT ...
FROM Suppliers a
CROSS JOIN Months b
LEFT JOIN Transactions c
ON a.Supplier = c.Supplier
AND b.year = c.year
AND b.month = c.month
WHERE ...
这应该为每个供应商提供至少一行,年,月,最终在交易中使用空值。然后你可以分组并总结。