MS sql子分组

时间:2013-10-23 18:55:45

标签: sql sql-server-2008

使用MS SQL 2012

有一张包含3列我关心的表

子类别ID(int) 制造商(nvarchar) 模型(nvarchar)

我想参加十大最受欢迎的制造商(表中排名最多的制造商),然后为这10家制造商中的每一家获得10个最受欢迎的子目录 然后在每个子类别中获得前5个最受欢迎的模型。

所以最后,假设有足够的数据,我应该最多有500个结果:

前10名制造商X前10个子类别X前5名模型

我到目前为止最接近这样做的是:

    SELECT COUNT(*), SubcategoryID, Manufacturer from dbo.Product
WHERE ManufacturerID IN
(
SELECT TOP 10 Manufacturerid FROM dbo.Product
WHERE Manufacturer != '' AND Manufacturer != 'NOT SPECIFIED' AND Manufacturer IS NOT NULL AND ManufacturerID IS NOT null
AND Deleted = 0 AND StatusID = 1
GROUP BY Manufacturerid
ORDER BY COUNT(*) DESC
)
GROUP BY Manufacturer, dbo.Product.SubcategoryID
ORDER BY  Manufacturer, COUNT(*) desc

但这并没有真正起作用,因为它为每个制造商提供了超过10条记录 - 我还没有尝试过获得该模型

感谢您的任何帮助,谢谢

编辑:我没有正确解释这一点 - 我希望获得每个子类别中排名前十的最常见制造商,而不是整个十大最受欢迎的制造商。

换句话说:

select top 10 manufacturers from product where subcategoryid = 123 group by manufacturer order by count(*) desc

但我希望表格中的每个子类别都有。然后是每个子类别/制造商中的前5个模型

1 个答案:

答案 0 :(得分:0)

在您的示例中,您不会将模型限制为每个制造商的前10名。

看看这是否有效......

SELECT Manufacturer, Model, SubCategoryID
FROM Product
WHERE Manufacturer IN (
        SELECT TOP 10 Manufacturer
        FROM Product
        GROUP BY Manufacturer
        ORDER BY COUNT(*) DESC )
AND SubCategoryID IN (
        SELECT TOP 10 SubCategoryID
        FROM Product a
        WHERE a.Manufacturer = Product.Manufacturer
        GROUP BY SubCategoryID
        ORDER BY COUNT(*) DESC )
AND Model IN (
        SELECT TOP 5 Model
        FROM Product a
        WHERE a.Manufacturer = Product.Manufacturer
        AND a.SubCategoryID = Product.SubCategoryID
        GROUP BY Model
        ORDER BY COUNT(*) DESC )