1

I have a table named 'sales' with following fields

salesid (type: int)
stime (type: datetime)
status (type: enum, values: remaining OR cancelled OR done)
... and other fields

I need a query that can output as

SalesDate     TotalSales    TotalDone      TotalRemaining     TotalCancelled
2010-11-06       10             5                3                 2
2010-11-06       15             14                1                 0

Anyone know how to achieve this?
Help appreciated, thanks.

2 Answers 2

3

You can use conditional summation to get the results you want.

select stime  as sales_date
      ,sum(1) as total_sales
      ,sum(case when status = 'remaining' then 1 else 0 end) as total_done
      ,sum(case when status = 'cancelled' then 1 else 0 end) as total_remaining
      ,sum(case when status = 'done'      then 1 else 0 end) as total_cancelled
  from sales
 group by stime;

You can also use COUNT(expr) and exploit the fact it doesn't include NULLS, but personally I find that the above best conveys the intent of the developer.

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

Comments

1

Use a CASE statement in your SELECT to create pseudo columns using the status values of remaining, cancelled and done

SELECT     
     date(stime),
     COUNT(salesid),
     SUM(CASE status WHEN 'done' THEN 1 ELSE 0 END) as TotalDone,
     SUM(CASE status WHEN 'remaining' THEN 1 ELSE 0 END) as TotalRemaining, 
     SUM(CASE status WHEN 'cancelled' THEN 1 ELSE 0 END) as TotalCancelled 
FROM  sales
GROUP BY date(stime)

Note: This is what i was trying to refer to. I think this should work but i have no access to MySQL to try out the syntax and verify it. Sorry about that. But this should get you going.

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.