我试图在表中选择两列(ID和状态)。该表应显示每个ID的最大值的状态。我尝试过其他一些例子但似乎没什么用。
原始数据结构:
ID state value (FLOAT)
1 TX 921,294,481
1 SC 21,417,296
1 FL 1,378,132,290
1 AL 132,556,895
1 NC 288,176
1 GA 1,270,986,631
2 FL 551,374,452
2 LA 236,645,530
2 MS 2,524,536,050
2 AL 4,128,682,333
2 FL 1,503,991,028
因此,结果数据结构应如下所示:
ID STATE (Max Value)
1 FL
2 AL
佛罗里达州和阿拉巴马州的ID群体中拥有最大的价值。
任何帮助都会对此非常感激。我确实找到了一个SO答案here,但无法让答案对我有用。
答案 0 :(得分:37)
对于SQL Server(以及具有窗口函数的其他产品):
SELECT *
FROM
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY value desc) as rn
FROM
UnnamedTable
) t
WHERE
t.rn = 1
答案 1 :(得分:7)
一种解决方案,基于value
为数字的假设:
SELECT
[ID],
[State],
[Value]
FROM
(
SELECT
[ID],
[State],
[Value],
Rank() OVER (PARTITION BY [ID] ORDER BY [Value] DESC) AS [Rank]
FROM [t1]
) AS [sub]
WHERE [sub].[Rank] = 1
ORDER BY
[ID] ASC,
[State] ASC
如果具有相同State
的多个ID
具有相同的Value
,则它们将获得相同的Rank
。这与使用返回唯一行号的Row_Number
不同,但是顺序是任意选择的。 (另见:SQL RANK() versus ROW_NUMBER())
答案 2 :(得分:7)
您可以使用子查询来获得此结果:
select t1.id, t1.[state] MaxValue
from yourtable t1
inner join
(
select id, max(value) MaxVal
from yourtable
group by id
) t2
on t1.id = t2.id
and t1.value = t2.maxval
order by t1.id