嵌套组在SQL Server中选择

时间:2015-02-25 18:07:32

标签: sql-server

我正在执行以下SELECT语句,以查看我的每个制造商在我的数据库中有多少个Reps,这很好用:

SELECT ManufacturerId, COUNT(*) AS RepCount 
FROM ManufacturerSalesReps WHERE IsDeleted=0
GROUP BY ManufacturerID
ORDER BY  COUNT(*) 

所以这给了我ManufacturerId和代表的数量,但我真正需要的是不同重复数的制造商数量。所以我想通过RepCount从上面的SELECT中分组结果。

我如何做到这一点?

2 个答案:

答案 0 :(得分:1)

我想不出其他的东西,但是:

SELECT T.RepCount, COUNT(*) AS ManufacturerCount
FROM (
    SELECT ManufacturerId, COUNT(*) AS RepCount 
    FROM ManufacturerSalesReps
    WHERE IsDeleted=0
    GROUP BY ManufacturerID
) AS T
GROUP BY T.RepCount
ORDER BY  COUNT(*) 

这是正确的还是完全愚蠢的。

答案 1 :(得分:0)

windowing functions

SELECT ManufacturerId, COUNT(*), 
count(ManufacturerId) over (partition by COUNT(*)) num_man AS RepCount 
FROM ManufacturerSalesReps WHERE IsDeleted=0
GROUP BY ManufacturerID
ORDER BY  2