我有两张桌子
-----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 :(得分:1)
您可以使用INNER JOIN
和GROUP 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
答案 1 :(得分:0)
您可以使用month进行加入,然后使用sum和group by进行总计
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)
答案 2 :(得分:0)
试试这个,应该有效:
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