在SQL Server中提示

时间:2017-11-07 17:47:06

标签: sql sql-server

说我有以下表格的数据

ID
1
2
2
2
3
4
4
4

我怎么能算一下?所以结果将是

n count
1  2
2  0
3  2
SQL Server中的

请注意,n!= ID。 n是distincs(1),double(2),triples(3)的数量。所以这与以前的问题不同。我想按计数分组,而不是按ID分组。

2 个答案:

答案 0 :(得分:3)

使用聚合聚合:

select cnt, count(*)
from (select id, count(*) as cnt
      from t
      group by id
     ) t
group by cnt
order by cnt;

注意:这不会返回0行。如果您确实需要,则需要left join

select v.cnt, count(t.id)
from (values (1), (2), (3)) v(cnt) left join
     (select id, count(*) as cnt
      from t
      group by id
     ) t
     on v.cnt = t.cnt
group by v.cnt
order by v.cnt;

答案 1 :(得分:1)

您可以使用内联表:

步骤1将聚合它们以确定哪个数字是“单个”,“双重”或“三重”。

SELECT
  `ID`,
  COUNT(`ID`) AS `count`
FROM
  `nums`
GROUP BY
  `ID`;

这给了你:

ID   | Count 
-------------
1    | 1
2    | 3
3    | 1
4    | 4

然后你计算每一个的数量:

SELECT 
  `count` AS `n`,
  COUNT(`count`) AS `count`
FROM
  (
    SELECT
      `ID`,
      COUNT(`ID`) AS `count`
    FROM
      `nums`
    GROUP BY
      `ID`
    ) AS `counts`
GROUP BY
  `count`
ORDER BY
  `count`

哪个给你

 n   | Count 
-------------
1    | 2
3    | 2

SQLFiddle