2017-03-10 74 views
0

我有兩個表運行總計將兩個表

-----Dates-----   ------Sales------ 
Date | Month   Date | Quantity 
---------------   ------------------ 
09/06/16| Jun   09/06/16| 2 
09/07/16| Jul   15/07/16| 11 
19/09/16| Sep   19/09/16| 12 
21/09/16| Sep   09/07/16| 33 
17/11/16| Nov   21/09/16| 45 

我需要寫一個SQL查詢來計算一個月

,每次我都能做這種方式運行總銷售額的?

SELECT Month, 
(SELECT SUM(Quantity) FROM Sales WHERE Month<=Dates.Month) 
FROM Dates, Sales 
WHERE Dates.Date = Sales.Date 
ORDER BY Month 

我覺得有什麼不對我的思維方式,但我沒有一個數據庫來證明這一點

+0

如果您沒有數據庫,如何運行查詢?您需要在「Where」後面加上「Group By Month」。 –

+0

澄清...鑑於「09/07/16 | Jul'在左邊的桌子上,你是否希望在那個日期或之前的16月7日所有的訂單? – dana

+2

你正在使用的數據庫 – scaisEdge

回答

1

您可以使用INNER JOINGROUP BY

SELECT Dates.Month, SUM(Quantity) 
FROM Dates INNER JOIN Sales ON Dates.Date = Sales.Date 
WHERE Sales.Month <= Dates.Month 
GROUP BY Dates.Month 
ORDER BY Dates.Month 
0

你可以用一個月的總

SELECT month(d.date), SUM(s.Quantity) 
    FROM Dates d 
    LEFT JOIN Sales S on month(d.date) = month(s.date) 
    ORDER BY month(d.date) 
加入再總結和GROUP BY
0

試試這個,應該禾rk:

WITH CTE 
AS 
(
Select DateName(mm,D.Date) as Month,MONTH(D.Date) as UsedByOrderByLater,Sum(S.Quantity) as SumForCurrentMonth 
FROM Dates as D 
    Inner Join Sales as S 
    ON S.Date = D.Date 
Group by DateName(mm,D.Date),MONTH(D.Date) 
) 
Select CTE.Month,CTE.SumForCurrentMonth , 
SUM(CTE.SumForCurrentMonth) OVER(Order by CTE.UsedByOrderByLater 
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as runningtotal 
from CTE