customer price date
123 100 1-Jan-15
321 200 2-Jan-15
123 10 3-Jan-15
123 50 4-Jan-15
321 150 5-Jan-15
123 100 6-Jan-15
123 300 7-Jan-15
321 500 8-Jan-15
123 700 9-Jan-15
I would like to take see SUM(Price) between dates 3-Jan and 7-Jan group by customer
Something like:
select customer,sum(price) from table group by customer
having date between 3-Jan-2015 and 8-Jan-2015
This prompts me to have date
either in the select
or group by
clause. When I include it, it groups by Date also.
Desired output is:
123 460
The HAVING
clause filters results after the grouping and aggregation, so in order to do this any fields you want in the HAVING
clause must be in the GROUP BY
or SELECT
lists. The WHERE
clause filters the rows before doing the grouping and aggregation.
To get the results you want, simply move the date between...
condition into a WHERE
clause:
SELECT customer,SUM(price)
FROM table
WHERE date BETWEEN 3-Jan-2015 AND 8-Jan-2015
GROUP BY customer