按名称选择每个记录组的最大值

时间:2014-08-14 07:11:41

标签: sql-server tsql

我有一个包含多个列的表:

Name  Price    Date   ...
a     100      .....
b     110      .....
c     90       .....
a     130      .....
b     60       .....
d     200      .....
c     5        .....

我想写一个查询,它会给我每个名字的最高价格:

a   130     .....
b   110     .....
c   90      .....
d   200     .....

5 个答案:

答案 0 :(得分:1)

试试这个:

SELECT  *
FROM    
        (
          SELECT *, 
                 ROW_NUMBER() OVER (PARTITION BY Name 
                                    ORDER BY Name ASC, Price DESC) AS RN
          FROM  Table
        ) AS T
WHERE   RN = 1

答案 1 :(得分:0)

使用此

SELECT tbl1.* FROM table_1 tbl1 INNER JOIN(
    SELECT name,MAX(price) price FROM table_1 GROUP BY name) tbl2
        ON tbl1.name = tbl2.name AND tbl1.price = tbl2.price

代码改革;)

答案 2 :(得分:0)

;with cte as(
    select
        rn = row_number() over(partition by Name order by Price desc),
        *
    from <table name>
)
select
    <columns>
from cte
where rn = 1

答案 3 :(得分:0)

我发现最好通过自我加入来做到这一点:

  • 首先,内部查询准备的Name1Name2的列表具有相同的Name但它们的Price是不同的,
  • 然后,按Name分组,以max()找出每个Name的最高价格

查询:

select Name1, max(Price1)

(
    select
        tbl1.Name Name1, tbl1.Price Price1,
        tbl2.Name Name2, tbl2.Price Price2
    from TableName tbl1 left join TableName tbl2
        on tbl1.Name = tbl2.Name
        and tbl1.Price != tbl2.Price
)ds
group by Name1

输出

Name  |  Price
---------------
a     |  130
b     |  110
c     |  90
d     |  200

答案 4 :(得分:-1)

select Name, Price, Date from (select max(Price)as p, Name as n from TableName 
group by Name) as A 
inner join 
(select * from from TableName where A.p=price and A.n=Name) as B

试试这个。