COUNT CASE WHEN的输出

时间:2019-05-23 18:58:26

标签: sql postgresql

我需要对psql实例上查询的输出进行计数。

我尝试过使用多种不同的配置使其成为子查询。

我想获取此查询的输出,并对新创建的测试组列进行计数。

SELECT userid,
   CASE WHEN COUNT(type) filter (WHERE type = 'web') <= COUNT(type) filter (WHERE type = 'mobile') THEN 'GROUPA'
   ELSE 'GROUPB'
   END AS testgroup  FROM logins
   GROUP BY userid
   ORDER BY userid;

输出

enter image description here

期望的输出

enter image description here

1 个答案:

答案 0 :(得分:2)

一种方法是子查询:

SELECT testgroup, COUNT(*)
FROM (SELECT userid,
             (CASE WHEN COUNT(type) filter (WHERE type = 'web') <= COUNT(type) filter (WHERE type = 'mobile')
                   THEN 'GROUPA'
                   ELSE 'GROUPB'
              END) AS testgroup
     FROM logins
     GROUP BY userid
    ) u
GROUP BY testgroup