0

使用 MS SQL 2012

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

SubcategoryID (int) 制造商 (nvarchar) 型号 (nvarchar)

我想选取最受欢迎的 10 个制造商(表中条目最多的制造商),然后为这 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 多条记录——而且我还没有尝试获取模型

感谢任何帮助,谢谢

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

换句话说:

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

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

4

1 回答 1

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 )
于 2013-10-23T19:16:13.410 回答