简体   繁体   中英

MySQL multiple count in single query

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM