Group By Query mysql

时间:2012-03-08 00:07:37

标签: mysql

我有一个包含以下值的表格

Name     DatePurchased     QuantityPurchased

A      2/3/2012             1
A      2/4/2012             1 
A      2/5/2012             2
B      2/2/2012             1
B      2/3/2012             2

I want to output the following

Name        DatePurchased         QuantityPurchased

A            2/3/2012               1
A            2/4/2012               2      // as I have purchased 2 upto this date
A            2/5/2012               4      // as I have purchased 4 upto this date
B            2/2/2012               1
B            2/3/2012               3

我的查询

SELECT Name,  `DatePurchased` , SUM(QuantityPurchased) 
FROM table1
GROUP BY DatePurchased

没有正确的数学运算。我知道什么是错的,但无法找出解决方案。

由于

3 个答案:

答案 0 :(得分:1)

重写答案,第一次误读。现在我知道你想要一个总计。我相信这样的事情应该有效。

Select B.Name,B.DatePurchased,SUM(B.QuantityPurchased)
FROM Table1 AS A
INNER JOIN Table1 AS B
ON A.Name=B.Name AND B.DatePurchased <= A.DatePurchased
GROUP BY B.Name,B.DatePurchased

答案 1 :(得分:1)

尝试:

SELECT t1.Name, t1.DatePurchased, SUM(t2.QuantityPurchased)
FROM table1 t1
LEFT JOIN table1 t2
ON t1.Name=t2.Name AND t1.DatePurchased >= t2.DatePurchased
GROUP BY Name, t1.DatePurchased

这会在{名}中将table1加入其中,并且t1的日期始终至少为t2个日期,并总结t2 s QuantityPurchased (对于每个名称,日期为t1)。

(尝试使用SELECT *执行相同的查询,而不使用SUMGROUP BY查看已加入的表格。然后SUMGROUP BY将变得清晰)。

答案 2 :(得分:0)

希望它有所帮助!

SELECT Name,  `DatePurchased` , SUM(QuantityPurchased) 
FROM table1
GROUP BY Name, DatePurchased
ORDER BY Name, DatePurchased