从表格中按产品组选择最畅销尺寸

时间:2015-07-21 10:11:03

标签: sql sql-server sql-server-2008 tsql

我有一个叫Orders的表。共有三列:CustomerIDProductGroupSize

如何从此表中TOPProductGroup销售尺寸?

我可以用

逐一进行
SELECT TOP 1 Count(customerid) as customers, ProductGroup, Size 
FROM Orders 
WHERE ProductGroup = xxx 
GROUP BY ProductGroup, Size
ORDER BY Count(customerid) DESC

但是,我想立即获得完整的清单。

5 个答案:

答案 0 :(得分:2)

不确定,但它可能对你有帮助。

Declare @temp table(CustomerID int, ProductGroup varchar(10), Size int)

insert into @temp
Select 1,'ABC',15 union all
Select 2,'ABC',10 union all
Select 3,'XYZ',12 union all
Select 4,'ABC',15 union all
Select 3,'XYZ',12 union all
Select 3,'XYZ',12 union all
Select 3,'XYZ',15 union all
Select 3,'XYZ',11 union all
Select 3,'XYZ',12 

Select * from (
Select RANK() Over(PARTITION BY ProductGroup order by customers desc) RankVal,customers,ProductGroup, Size 
from (
SELECT Count(CustomerID) as customers, ProductGroup, Size 
FROM  @temp 
GROUP BY ProductGroup, Size
) T
)T1
WHERE RankVal = 1

答案 1 :(得分:1)

请使用SQL Count using Partition By clause

检查以下SELECT查询
;with cte as (
    SELECT 
        Distinct ProductGroup, Size, 
        COUNT(*) OVER (Partition By ProductGroup, Size) cnt
    FROM Customers
)
select 
    ProductGroup, Size, cnt
from (
    select *, 
        rn = ROW_NUMBER() OVER (Partition By ProductGroup Order By cnt desc)
    from cte
) t 
where rn = 1

答案 2 :(得分:0)

您希望每个ProductGroup拥有最畅销的产品。实现此目的的方法是使用group by,例如通过

SELECT ProductGroup, MAX(size)
FROM orders
GROUP BY ProductGroup

通过这种方式,您可以获得一个结果表,每个ProductGroup一列,以及此产品组的最大尺寸。

答案 3 :(得分:0)

您可以尝试使用MAX运算符并将SQL放在子查询中,如下所示(未经测试):

  SELECT MAX(customers), ProductGroup, Size FROM Orders GROUP BY ProductGroup, Size HAVING MAX(customers) = 
    SELECT MAX(customers) AS myMax FROM (
        SELECT Count(customerid) as customers, ProductGroup, Size
        FROM Orders 
        GROUP BY ProductGroup, Size) AS O
    GROUP BY ProductGroup, Size

答案 4 :(得分:0)

您可以使用聚合函数max()来选择最大尺寸,并根据ProductGroup对其进行分组。

SELECT COUNT(customerid) as customers, ProductGroup, MAX(Size) FROM 
    Orders WHERE Size IN (SELECT MAX(Size) FROM Orders) GROUP BY ProductGroup
    ORDER BY customerid DESC;

请注意,此查询尚未经过测试,我想知道如果您只选择每个产品组的最大尺寸,为什么还需要获取customerid的数量。