我有两个查询分别给出了购买的工作单位数和客户消耗的工作单位数。
我正在研究SQL Server 2014
WUBought查询返回类似这样的例子:
Customer Year Month UnitBought
Cust1 2015 6 50
Cust2 2014 7 100
Cust1 2013 10 30
Cust3 2015 2 40
另一个查询返回客户端使用的数字:
Customer Year Month UnitConsumed
Cust1 2015 2 6
Cust1 2015 5 20
Cust2 2015 3 8
Cust1 2015 4 3
Cust3 2015 2 10
我基本上想要做的,是每个月购买的东西的总和,减去已经消耗的东西。以下是Cust1的前六个月我想要的结果示例:
Customer Year Month Remaining
Cust1 2015 1 30
Cust1 2015 2 24
Cust2 2015 3 24
Cust1 2015 4 21
Cust3 2015 5 1
Cust3 2015 6 51
从每月列出的表中返回使用UNION ALL购买的WU的查询,即使没有值也可以获得每个月:
SELECT Customer, [Year], [Month], SUM(UOBought) AS UORest
FROM WU_Bought
GROUP BY [Customer], [PurchaseDate]
UNION ALL
SELECT '' AS Customer, [Year], [Month], '' AS UORest
FROM Months
GROUP BY [Year], [Month]
以下是每月对每个购买单位求和的查询,使用相同的联合声明:
SELECT Customer, [Year], [Month], SUM(TotalConsumed) * -1 AS UORest
FROM WUConsumed
GROUP BY Customer, Year, Month
UNION ALL
SELECT '' AS Customer, [Year], [Month], '' AS UORest
FROM EveryMonths
GROUP BY Year, Month
现在我想我必须调整第一个,强制它保留前一个总和,但我不知道我该怎么做。
答案 0 :(得分:0)
这对你有用吗?
SELECT b.customer_id, b.year, b.month, SUM(b.units_bought) AS units_bought, ISNULL(c.units_consumed,0) AS units_consumed, SUM(b.units_bought) - ISNULL(c.units_consumed,0) AS units_remaining
FROM Bought b
LEFT JOIN Consumed c
ON b.customer_id = c.customer_id AND b.year = c.year AND b.month = c.month
GROUP BY b.customer_id, b.year, b.month
答案 1 :(得分:0)
好的,我让它运转了。
使用自2012年以来可用的SQL Server功能,我所做的真的很“简单”: ROWS UNBOUNDED PRECEDING
Here is a pretty clear article关于此功能。
我创建了另一个视图,使用UNION ALL子句(称为“WU_Closing_View”)对有关已消耗和已购买单元的查询的结果进行分组,然后在其中使用ROWS UNBOUNDED PRECEDING:
SELECT Customer, Year, Month, SUM(Closing) OVER(PARTITION BY Customer ORDER BY Year, Month ROWS UNBOUNDED PRECEDING) AS Closing
FROM WU_Closing_View
GROUP BY Customer, Year, Month, Closing
UNION ALL
SELECT '' AS Customer, Year, Month, '' AS Sum_bought
FROM Months
GROUP BY Year, Month
ORDER BY Customer, Year, Month
请注意,我使用了PARTITION BY
,以便按客户端求和。因为我想每个月都在一个SSRS矩阵中显示,所以我添加了一个“UNION ALL”,指向一个每年和每月都有一个空客户端的表,从2010年到2017年。但如果你不这样做,它是可选的需要每个月的进化。
可能有一种更简单的方法,但那是我迄今为止找到的方式。