我有一个查询,它使用多个连接返回列的sum()。问题是值与每个连接相乘。
示例代码:
select c.Categories, sum(os.OpeningStock), sum(cs.[ClosingStock])
from #categories c
join #openingstocks os on c.Categories = os.Categories
join #closingstocks cs on c.categories=cs.Categories
group by rollup(c.Categories)
由于我使用了两个连接,因此值在这里成倍增加。
我正在使用sum(distinct)并且它正在呈现正确答案但是还有其他解决方案吗?
答案 0 :(得分:2)
SUM(DISTINCT)
将返回错误的结果
您可以使用
WITH os
AS (SELECT Categories,
SUM(os.OpeningStock) AS OpeningStock
FROM #openingstocks
GROUP BY Categories),
cs
AS (SELECT Categories,
SUM(os.[ClosingStock]) AS [ClosingStock]
FROM #closingstocks
GROUP BY Categories)
SELECT c.Categories,
SUM(os.OpeningStock),
SUM(cs.[ClosingStock])
FROM #categories c
JOIN os
ON c.Categories = os.Categories
JOIN cs
ON c.categories = cs.Categories
GROUP BY rollup( c.Categories )