如何将下面的 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;
如何将下面的 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;
这样做合并上面的查询:
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
上面的答案将为您提供 action_2 的多行,而您似乎只想要 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;
SELECT COUNT(user_id), date
FROM table
WHERE action IN ('action_1', 'action_2)
GROUP BY action, date
你的查询可以是这样的
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()
with 表达式将产生一个布尔值,如果action ='action_1'
然后结果将为 1,如果不是则为 0,所有这些都被求和并根据表达式结果产生计数