假设表包含以下颜色:
id integer,
name char(6),
status integer
并有以下数据:
id id2 type
--- ----- ----
01 Adam 1
02 Bob 1
03 Adam 2
04 Caymen 1
05 Ahmed 1
06 Basel 1
07 Ahmed 2
08 Bob 2
09 Ahmed 2
10 Mike 1
因此它基本上跟踪不同用户的状态进展。
我想对状态计数进行分组。换句话说,我想知道有多少用户只有1个状态,有多少有2个状态,有多少有3个状态等等。
预期的输出将是这样的:
num_of_statuses count
--------------- -----
1 3
2 2
3 1
我试过了,但还找不到解决方案。任何语法都可以。 SQL / MySQL的/ DB2 / Oracle的。
答案 0 :(得分:8)
您需要一个嵌套查询,如下所示:
select num_of_statuses, count(*)
from (
select id2, count(*) as num_of_statuses
from table1
group by id2
) A
group by num_of_statuses
在sqlfiddle上查看:http://sqlfiddle.com/#!2/ed95e/1
答案 1 :(得分:5)
WITH summary (fname, num_of_statuses) AS
( SELECT fname, COUNT(*) num_of_statuses
FROM basetablename GROUP BY fname
)
SELECT num_of_statuses, COUNT(*) AS peoplecount
FROM summary
GROUP BY num_of_statuses
;
答案 2 :(得分:2)
如果您不想使用嵌套查询,可以像这样避免:
SELECT DISTINCT
num_of_statuses = COUNT(*),
count = COUNT(*) OVER (PARTITION BY COUNT(*))
FROM atable
GROUP BY id
答案 3 :(得分:1)
你可以试试这个
SELECT DISTINCT NO_OF_STATUS, COUNT(NAME)
FROM (SELECT DISTINCT HT.NAME, COUNT(HT.STATUS) AS NO_OF_STATUS
FROM SO_HYPO_TABLE HT
GROUP BY HT.NAME) A
GROUP BY NO_OF_STATUS
ORDER BY NO_OF_STATUS
希望这有帮助