我有一个查询,该查询按某个列对表进行分组,并根据某些过滤提供一些汇总数据。当前,我知道如何实现查询的唯一方法是使用多个子查询,这似乎效率很低。假设我有下表:
user_id event_type value
1 click 4
2 click 2
1 click 1
4 close 5
2 open 3
我想按user_id
对数据进行分组并汇总以下信息:max_value
,min_click_value
。根据示例表格的能力,这是我希望看到的结果:
user_id max_value min_click_value
1 4 1
2 3 2
4 5 null
是否有一种无需子查询即可完成此操作的方法?到目前为止,这是可行的,但是感觉效率很低:
SELECT t1.user_id, max_value, min_click_value
(SELECT user_id, MAX(value) as max_value
FROM my_table
GROUP BY user_id) as t1
LEFT JOIN
(SELECT user_id, MIN(value) as min_click_value
FROM my_table
WHERE event_type = "click"
GROUP BY user_id) as t2
WHERE t1.user_id = t2.user_id
答案 0 :(得分:4)
条件聚合应该在这里起作用:
SELECT
user_id,
MAX(value) AS max_value,
MIN(CASE WHEN event_type = 'click' THEN value END) AS min_click_value
FROM yourTable
GROUP BY
user_id;
答案 1 :(得分:2)
使用条件聚合:
select user_id, max(value) as max_value
min(case when event_type = 'click' then value end) as min_click_value
from my_table
group by user_id;