进一步按计数分组

时间:2012-08-03 17:58:40

标签: sql sql-server-2008

当前SQL语句:

SELECT count(installUserID) as userCount
  FROM installUsers
  group by installationID

当前输出:

userCount
4
2
1
1
1
2
4
1
3
1

我正在尝试计算userCount为1,以及2等的次数......

所需输出的示例:

userCount = 1, 5 times
userCount = 2, 2 times
userCount = 3, 1 times
userCount = 4, 2 times

我浏览了互联网,我想我可以使用聚合函数做些事情,可能还有grouping,但我还不清楚如何用纯sql实现它。

2 个答案:

答案 0 :(得分:3)

您似乎想要计算次数。为此,您可以使用外部选择:

SELECT userCount, COUNT(*) AS userCountcount
FROM
(
    SELECT COUNT(installUserID) as userCount
    FROM installUsers
    GROUP BY installationID
) AS T1
GROUP BY userCount
ORDER BY userCount

答案 1 :(得分:3)

或者您可以使用CTE。也许过度杀戮但是非常方便。

WITH count_cte(usercount)
AS
(
  SELECT COUNT(installUserID) AS userCount
  FROM installUsers
  GROUP BY installationID
)

SELECT  usercount  ,COUNT(usercount) AS times  FROM count_cte GROUP BY usercount