SQL分组到范围?

时间:2017-11-02 09:48:35

标签: sql oracle

我有一张桌子" USER_ACTIVITY"像这样:

USER_ID, LOGINS, CITY
1         2        NY 
2         4        NY
3         10       NY
15        0        WS
...

我希望得到这样的结果:

CITY, DEAD_USERS, LOW_ACTIVITY, HIGH_ACTIVITY
NY     0           2             1 ....

这与Exaplus中的普通Oracle-SQL有关。

我真的不知道如何自己指定范围。谢谢!

1 个答案:

答案 0 :(得分:1)

COUNTCASE表达式一起使用:

SELECT City,
       COUNT( CASE WHEN logins = 0 THEN 1 END ) AS dead,
       COUNT( CASE WHEN logins BETWEEN 1 AND 3 THEN 1 END ) AS low_activity,
       COUNT( CASE WHEN logins > 3 THEN 1 END ) AS high_activity
FROM   user_activity
GROUP BY City