SQL中唯一行的聚合

时间:2013-11-01 15:58:49

标签: sql sql-server

我有以下独特行表:

Name        change  Number_of_Sales
Soby        2.22    8370
Sollerod    -1.06   11287
Sonderborg  2.60    6343
Sonderhald  11.43   1623
Sonderhald  10.93   2098

我想选择namechange,不包括重复的名称,以便Sonderhald只出现一次。我希望Sonderhald的最大值为Number_of_Sales

如何在SQL Server中执行此操作?

由于

2 个答案:

答案 0 :(得分:3)

SELECT t.name, t.change, t.number_of_sales
FROM your_table t
INNER JOIN (
        SELECT tt.name, MAX(tt.number_of_sales) AS max_number_of_sales 
        FROM your_table tt 
        GROUP BY tt.name
    ) tm ON t.name = tm.name AND t.number_of_sales = tm.max_number_of_sales

答案 1 :(得分:0)

您可以使用公用表表达式来执行此操作:

;
WITH    cte
          AS ( SELECT   Name,
                        Change,
                        Number_of_Sales,
                        ROW_NUMBER() OVER ( PARTITION BY name ORDER BY number_of_sales DESC ) AS RowNum
               FROM     your_table
             )
    SELECT  Name,
            Change,
            Number_of_Sales
    FROM    cte
    WHERE   RowNum = 1

http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx