什么是sum(distinct)的替代方案?

时间:2018-01-15 07:57:57

标签: sql-server

我有一个查询,它使用多个连接返回列的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)并且它正在呈现正确答案但是还有其他解决方案吗?

1 个答案:

答案 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 )