MySQL Sales Records – Select Units Sold and Total Units Sold

MySQL

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

My Database

My Expected Result

Best Answer

You need a conditional aggregate using CASE:

SELECT sr.itemID, sr.itemname,
   SUM(sr.itemunits) AS "Total Units Sold", 
   SUM(CASE WHEN date='2016-04-14' THEN sr.itemunits END) AS "Units Sold"
FROM salesrecord AS sr
WHERE date <= '2016-04-14'
GROUP BY sr.itemID, sr.itemname

I used a table-alias sr which improves readability.

And I added sr.itemID to GROUP BY, which is compliant with Standard SQL (and the latest version of MySQL)