我有兩個查詢分別給出了購買的工作單元數和客戶端使用的工作單元數。從兩個查詢中爲每行增加一列
我是一個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買了所有從每月列出一個表的查詢,以獲得每月甚至如果沒有價值:
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]
這裏是每月每求和買單元,與同工會語句的查詢:現在我覺得我必須調整的F
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
第一個,迫使它保留以前的總和,但我不知道我該怎麼做。
Namrehs,我不得不添加c.units_consumed到group by子句,因爲它給了我一個錯誤。我對這個查詢還有一些問題:不知何故,它不會保留之前購買的單位,我認爲,並且只給了我一個月客戶購買更多單位的結果。 –