我有一张表:
Status | Quantity | PeriodDate
------------------------------
100 | 2 | 2013-07-02
100 | 3 | 2013-07-02
100 | 5 | 2013-07-02
100 | 3 | 2013-07-03
100 | 1 | 2013-07-03
100 | 0 | 2013-07-04
100 | 0 | 2013-07-04
100 | 5 | 2013-07-04
100 | 6 | 2013-07-05
100 | 4 | 2013-07-06
100 | 8 | 2013-07-06
我需要选择数据,以便显示某个范围内每个不同日期的数量。我原本以为我可以做点什么:
SELECT DISTINCT PeriodDate, SUM(Quantity) as TotalQuantity where PeriodDate BETWEEN '2013-07-02' AND '2013-07-04'
但是这会返回一行,其中包含所有数量的总和。
我喜欢这样的事情:
TotalQuantity | PeriodDate
--------------------------
10 | 2013-07-02
4 | 2013-07-03
5 | 2013-07-04
6 | 2013-07-05
我如何实现这一目标?
答案 0 :(得分:4)
SELECT PeriodDate,
SUM(Quantity) as TotalQuantity
from your_table
where PeriodDate BETWEEN '2013-07-02' AND '2013-07-05'
group by PeriodDate
答案 1 :(得分:3)
区别同时适用于PeriodDate
和TotalQuantity
。您需要使用DISTINCT
。
GROUP BY
SELECT PeriodDate, SUM(Quantity) as TotalQuantity
FROM ???
WHERE PeriodDate BETWEEN '2013-07-02' AND '2013-07-04'
GROUP BY PeriodDate
解释:Distinct用于消除结果集中的重复行。