0

I have a table with values like the following

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

My query

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

does not do the math right. I know whats wrong but can't figure out the solution.

Thanks

2
  • Try replacing SUM() with COUNT(). This may or may not work depending on what results you get currently; please post the output your current query generates. Commented Mar 8, 2012 at 0:22
  • Count doesn't work either. I'll post my output Commented Mar 8, 2012 at 0:26

3 Answers 3

1

Try:

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

This joins table1 to itself within Name and such that t1s date is always at least t2s date, and sums up t2s QuantityPurchased (for each name,date in t1).

(Try performing the same query with SELECT *, and without the SUM and GROUP BY to see the joined table. Then the SUM and GROUP BY will become clear).

Sign up to request clarification or add additional context in comments.

Comments

1

Rewriting the answer, misread it the first time. Now I understand that you want a running total. I believe something like this should work.

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 Comment

That's not what OP wants - they want a cumulative sum up to each date.
0

hope it helps!

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.