如何在mysql中编写查询以获取如下数据?

时间:2014-12-20 11:01:22

标签: php mysql

我有像这样的 tbl_users

Uid       Fname     createddate    Active(0:inactive;1:active;2:pending)

1        user1      2014-12-14     1                              
2        user2      2013-11-18     0  
3        user3      2014-12-14     1

我想要的是......

根据日期有多少用户处于活动,非活动和待处理状态?

array(

[0]=>array(
      [date]=>2014-12-14
      [active]=2
      [inactive]=0
      [pending]=0
     )
[1]=>array(
      [date]=>2013-11-18
      [active]=0
      [inactive]=1
      [pending]=0
     )

 )

2 个答案:

答案 0 :(得分:3)

在Mysql中,条件求和很容易,可以表示为

select
createddate,
sum( Active = 1 ) as `active`,
sum( Active = 0 ) as `inactive`,
sum( Active = 2 ) as `pending`
from tbl_users
group by createddate

答案 1 :(得分:2)

尝试类似:

SELECT date, COUNT(CASE WHEN Active = 0 then 1 ELSE NULL END) as "Inactive",
             COUNT(CASE WHEN Active = 1 then 1 ELSE NULL END) as "Active",
             COUNT(CASE WHEN Active = 2 then 1 ELSE NULL END) as "Pending" 
FROM tbl_users
GROUP BY date