我有一个包含多个列的表:
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 .....
答案 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)
我发现最好通过自我加入来做到这一点:
Name1
和Name2
的列表具有相同的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
试试这个。