在多个条件下对单个列计数DISTINCT

时间:2015-12-01 16:35:49

标签: mysql mariadb

我有一张桌子,我希望在一段时间内得到DISTINCT个用户名。目前我正在运行此查询

SELECT DISTINCT username FROM user_activity WHERE company_id = 9 AND timestamp BETWEEN  '2015-09-00' AND '2015-10-01' AND action = "Login Success";

它运作良好,但是,我有多个公司,我想选择计数。如何扩展先前的查询以向我显示多个公司的不同计数?

select count(distinct username),
    sum(case when company_id = 1 then 1 else 0 end) A,
    sum(case when company_id = 9 then 1 else 0 end) B
from `user_activity` Where timestamp BETWEEN  '2015-09-00' AND '2015-10-01' AND action = "Login Success"

我做过类似的事情,但是,我没有得到正确的数字。理想情况下,我想将每个计数列为不同的值,以便于阅读,就像前面的查询所示。我不需要count(distinct username)列显示在我的结果中,只需要条件。

提前致谢。

1 个答案:

答案 0 :(得分:2)

如果你不介意两行而不是两列:

  SELECT company_id, COUNT(DISTINCT username)
    FROM user_activity
   WHERE company_id IN (1,9) 
     AND timestamp >= '2015-09-01'
     AND timestamp <  '2015-09-01' + INTERVAL 1 MONTH
     AND action = "Login Success"
GROUP BY company_id