简体   繁体   English

SQL中唯一行的聚合

[英]Aggregation of unique rows in SQL

I have the following table of unique rows: 我有以下独特行表:

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

I want to select name and change , excluding duplicate Names, so that Sonderhald only occurs once. 我想选择namechange ,不包括重复的名称,以便Sonderhald只出现一次。 I want the Sonderhald with the maximum Number_of_Sales . 我希望Sonderhald具有最大Number_of_Sales

How can I do this in SQL Server? 我怎么能在SQL Server中执行此操作?

Thanks 谢谢

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

You can use a common table expression to do this: 您可以使用公用表表达式来执行此操作:

;
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 http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM