SQL:2个不同的计数,在同一个字段中具有不同的where子句

时间:2012-08-15 17:55:57

标签: mysql

如何将以下2个查询合并为一个查询?

select count(distinct user_id) as action_1_count, date  
from table    
where action = "action_1"  
group by date;

select count(distinct user_id) as action_2_count, date
from table  
where action = "action_2"  
group by date;

4 个答案:

答案 0 :(得分:1)

这样做是为了合并以上查询:

SELECT date,
         CASE WHEN action  = "action_1" THEN COUNT(user_id) END AS Action1Count,
         CASE WHEN action  = "action_2" THEN COUNT(user_id) END AS Action2Count
  FROM table    
  WHERE action IN ("action_1", "action_2")
  GROUP BY date

答案 1 :(得分:0)

SELECT COUNT(user_id), date
FROM table
WHERE action IN ('action_1', 'action_2)
GROUP BY action, date

答案 2 :(得分:0)

您的查询可以像这样

SELECT COUNT(user_id), date FROM table WHERE action IN ('action_1', 'action_2') GROUP BY date

以下是使用SUM()函数的另一种方法,这应该可以解决问题

SELECT 
  SUM(action ='action_1') count_1,
  SUM(action ='action_2') count_2, 
  SUM(action ='action_1' OR action ='action_2') `full_count`,
  date 
FROM
 table 
GROUP BY date

SUM()与表达式一起使用将产生一个布尔值,如果action ='action_1'则结果为1,如果不是则为0,这将全部求和并根据表达式结果生成计数

答案 3 :(得分:0)

以上答案会为action_2提供多行,而看起来你只需要一行for action_2。

你可以使用联盟:

select '1', count(distinct user_id), date
from table
where action = "action_1"
group by 3
union
select '2', count(distinct user_id), max(date)
from table
where action = "action_2"
group by 3;