Mr Nemo Mr Nemo - 1 year ago 99
SQL Question

Conditional Sum SQL

I am very new to SQL and have been presented with, what seems to me, a complex task. I have a table which is generating the number of various fruit purchased on a given day. Thus:

G. A G.B
2016-06-01 Banana 45 0
2016-06-01 Pear 158 0
2016-06-01 apple 0 23
.... dates continue

I need to develop some kind of conditional sum to count how many types of fruit are bought with a specific grade on a specific date. So in the above case on the given date (2016-06-01) there would be 203 Grade A (G.A) bits of fruit and 23 Grade B (G.B) pieces of fruit.

Naturally some kind of

Sum(case when date=date then Grade else 0 ).

But, I am really baffled here. Please, any help would be greatly appreciated!!!!

Answer Source

A simple group clause should do the job here (Note: untested code)

select date, sum(grade_a) as grade_a_sum, sum(grade_b) as grade_b_sum
from sales
group by date;

This will give the grades for every date. Individual dates can then be selected if necessary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download