MySQL查询在同一个表上的查询中

时间:2013-10-04 14:17:23

标签: mysql sql subquery

我有一张表:

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

我如何实现这一目标?

2 个答案:

答案 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)

区别同时适用于PeriodDateTotalQuantity。您需要使用DISTINCT

,而不是使用GROUP BY
SELECT PeriodDate, SUM(Quantity) as TotalQuantity 
FROM ???
WHERE PeriodDate BETWEEN '2013-07-02' AND '2013-07-04'
GROUP BY PeriodDate

解释:Distinct用于消除结果集中的重复行。

进一步解释:http://www.mysqltutorial.org/mysql-distinct.aspx