I am trying to Select Units Sold and Total Units Sold from a Sales record table using.
When I use this Query, I can get the Units Sold for '2016-04-14'
SELECT salesrecord.itemID, salesrecord.itemname,
SUM(salesrecord.itemunits) AS `Units Sold` ,
SUM(salesrecord.itemunits)
WHERE `date`='2016-04-14'
GROUP BY salesrecord.itemname
And When I Use this query, I can get the Total units Sold till date
SELECT salesrecord.itemID, salesrecord.itemname,
SUM(salesrecord.itemunits) AS `Total Units Sold` ,
SUM(salesrecord.itemunits)
WHERE `date`<='2016-04-14'
GROUP BY salesrecord.itemname
What I will like to do is to get both "Units Sold" And "Total Units Sold" on a single table as shown in image attached
Best Answer
You need a conditional aggregate using
CASE
:I used a table-alias
sr
which improves readability.And I added
sr.itemID
toGROUP BY
, which is compliant with Standard SQL (and the latest version of MySQL)