开发者

MySQL multiple count in single query

开发者 https://www.devze.com 2023-01-28 20:27 出处:网络
I have a table named \'sales\' with following fields salesid (type: int) stime (type: datetime) status (type: enum, values: remaining OR cancelled OR done)

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

开发者_C百科
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消