聚合函数内部的SQL聚合函数

时间:2019-07-23 20:13:26

标签: sql aggregate-functions

我知道不可能嵌套聚合函数。但是我想实现这样的目标,并且对如何降低这种性能感到困惑。

SELECT 
  date, 
  count(CASE WHEN SUM(active_time) > 5 THEN user_id END) AS total_active_users, 
  count(CASE WHEN SUM(active_time) > 5 AND is_admin = true THEN user_id END) AS total_active_admin_users
FROM
(
  SELECT date, user_id, user_name, active_time, is_admin FROM users
)
GROUP BY date

如果有人可以提出实现此目标的方法,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

也许您想要这样的东西:

select date, 
       sum(case when sum_active_time > 5 then 1 else 0 end) as  total_active_users, 
       sum(case when sum_active_time > 5 and is_admin then 1 else 0 end) as  total_active_admin_users
from (select u.*, sum(active_time) over (partition by user_id) as sum_active_time
      from users
     ) u
group by date;

但是,我希望user_id在称为users的表中是唯一的。这使我想知道为什么您需要进行计数或求和。因此,您可能需要:

select date, 
       sum(case when active_time > 5 then 1 else 0 end) as  total_active_users, 
       sum(case when active_time > 5 and is_admin then 1 else 0 end) as  total_active_admin_users
from users
group by date;

答案 1 :(得分:0)

SELECT date, 
       COUNT(user_id) as total_active_users,
       COUNT(CASE WHEN is_admin = 1 THEN user_id END ) as total_active_admin_users
FROM (
     SELECT  date, is_admin, user_id
     FROM users
     GROUP BY date, is_admin, user_id
     HAVING SUM(active_time) > 5
    ) t
GROUP BY date