3

假设表包含以下列:

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。

4

4 回答 4

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

于 2012-04-30T22:14:48.273 回答
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
;
于 2012-04-30T22:17:20.447 回答
2

如果您不想使用嵌套查询,可以这样避免:

SELECT DISTINCT
  num_of_statuses = COUNT(*),
  count           = COUNT(*) OVER (PARTITION BY COUNT(*))
FROM atable
GROUP BY id
于 2012-05-02T08:31:16.050 回答
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

希望这可以帮助

于 2012-05-02T07:32:24.623 回答