在SQL表中查找最高分的存储过程

时间:2016-06-14 16:47:06

标签: sql

+-------+-----------+-------+
| Name  |   Date    | Score |
+-------+-----------+-------+
| Name1 | 1/3/2016  |    80 |
| Name2 | 1/5/2016  |    76 |
| Name3 | 1/29/2016 |    77 |
| Name4 | 1/30/2016 |    40 |
| Name4 | 1/17/2016 |    79 |
| Name5 | 1/1/2016  |    90 |
| Name2 | 1/3/2016  |    79 |
| Name5 | 1/27/2016 |    92 |
| Name2 | 1/27/2016 |    99 |
| Name1 | 1/21/2016 |    93 |
| Name2 | 1/3/2016  |    70 |
| Name1 | 2/15/2016 |    80 |
| Name3 | 3/31/2016 |    84 |
+-------+-----------+-------+

我有这张桌子,需要在给定的时间内(即2016年1月1日至2016年1月31日之间)找到每个名字的最高分,并显示姓名,日期和最高分。

请帮忙!谢谢 - Humberto Goez

3 个答案:

答案 0 :(得分:1)

您将遇到重复行的问题,因为您没有显示主键。此查询可以使用,但最好使用主键

当然,这只是SQL ......

SELECT Name, [Date], Score
FROM MyTable T1
WHERE T1.Score = (SELECT MAX(T2.Score) 
                  FROM MyTable T2 
                  WHERE T2.Name = T1.Name)
    AND [Date] >= @StartDate
    AND [Date] <= @EndDate

答案 1 :(得分:1)

如果您使用SQL Server,则可以使用:

DECLARE @start_date DATE = '2016-01-01T00:00:00'
       ,@end_date DATE = '2016-01-31T00:00:00';

SELECT TOP 1 WITH TIES [Name],[Date],[Score]
FROM tab_name t
WHERE [Date] BETWEEN @start_date AND @end_date
ORDER BY RANK() OVER(PARTITION BY Name ORDER BY Score DESC);

LiveDemo

答案 2 :(得分:0)

一个好的方法是CTE。示例查询如下所示:

declare @StartDate datetime = '2016-01-01',
        @EndDate datetime = '2016-06-01'
;with scores as (
SELECT Name, [Date], Score,
row_number() over(partition by name /*start over each name*/ 
                  order by Score desc /*top first*/,[Date] /*earlier first*/) rn
FROM MyTable
)
select * from scores
where rn = 1