在一列上选择distinct,返回多行和多列

时间:2016-01-08 16:27:52

标签: sql sql-server

使用此查询

SELECT 
    product, customer, sum(sales) as topSales 
FROM 
    invoices 
WHERE 
    product in (//lots of product id's here)
GROUP BY 
    product, customer 
ORDER BY 
    topSales DESC

我得到的结果集包含产品的所有买家,按销售额递减的顺序排列。

PRODUCT  CUSTOMER    topSales
=============================
banana   Chris       50.35
banana   Eric        34.87
cookie   Emmy        54.54
apple    John        78.67
banana   Derek       33.87
banana   Sally       21.76
apple    Henry       65.78
cookie   Yoyo        24.67
milk     Chris       30.43
milk     Henry       22.43

我只想要每个产品的顶级买家,它应该看起来像这样

PRODUCT  CUSTOMER    topSales
=============================
banana   Chris       50.35
cookie   Emmy        54.54
apple    John        78.67
milk     Chris       30.43

我怎样才能得到这样的结果?我需要获得不同的产品,但仅限于顶级买家。

3 个答案:

答案 0 :(得分:2)

您可以使用窗口功能执行此操作:

SELECT *
FROM (SELECT product, customer, sum(sales) as topSales,
             ROW_NUMBER() OVER (PARTITION BY product ORDER BY SUM(sales) DESC) as seqnum
      FROM invoices 
      WHERE product in(//lots of product id's here)
      GROUP BY product, customer
     ) pc
WHERE seqnum = 1
ORDER BY topSales DESC;

答案 1 :(得分:1)

来自:https://dba.stackexchange.com/questions/1002/how-to-get-the-max-row
(有关如何获得最佳排名的更多示例,请参阅链接)

--ranking + derived table
SELECT
    C.*
FROM
    (SELECT ROW_NUMBER() OVER (PARTITION BY product ORDER BY topSales ) AS topBuyer,
product, customer, sum(sales) as topSales FROM invoices 
WHERE product in(//lots of product id's here)
GROUP BY product,customer ORDER BY topSales DESC) C
WHERE
    C.topBuyer = 1
ORDER BY
    C.product

答案 2 :(得分:0)

我们可以通过使用IN条件和MAX来实现相同的结果

DECLARE @Invoices TABLE 
    (PRODUCT varchar(6), CUSTOMER varchar(5), topSales decimal(18,2))
;

INSERT INTO @Invoices
    (PRODUCT, CUSTOMER, topSales)
VALUES
    ('banana', 'Chris', 50.35),
    ('banana', 'Eric', 34.87),
    ('cookie', 'Emmy', 54.54),
    ('apple', 'John', 78.67),
    ('banana', 'Derek', 33.87),
    ('banana', 'Sally', 21.76),
    ('apple', 'Henry', 65.78),
    ('cookie', 'Yoyo', 24.67),
    ('milk', 'Chris', 30.43),
    ('milk', 'Henry', 22.43)
;
select PRODUCT, CUSTOMER, topSales from @Invoices  t 
where t.topSales in 
(select MAX(topSales) 
from @Invoices 
where PRODUCT = t.PRODUCT) --AND  product in (//lots of product id's here)