Using a SELECT statement within a WHERE clause

后端 未结 7 2103
孤街浪徒
孤街浪徒 2020-12-17 18:42
SELECT * FROM ScoresTable WHERE Score = 
  (SELECT MAX(Score) FROM ScoresTable AS st WHERE st.Date = ScoresTable.Date)

Is there a name to describe

相关标签:
7条回答
  • 2020-12-17 19:23

    There's a much better way to achieve your desired result, using SQL Server's analytic (or windowing) functions.

    SELECT DISTINCT Date, MAX(Score) OVER(PARTITION BY Date) FROM ScoresTable
    

    If you need more than just the date and max score combinations, you can use ranking functions, eg:

    SELECT  *
    FROM    ScoresTable t
    JOIN (   
        SELECT 
            ScoreId,
            ROW_NUMBER() OVER (PARTITION BY Date ORDER BY Score DESC) AS [Rank] 
            FROM ScoresTable
    ) window ON window.ScoreId = p.ScoreId AND window.[Rank] = 1
    

    You may want to use RANK() instead of ROW_NUMBER() if you want multiple records to be returned if they both share the same MAX(Score).

    0 讨论(0)
提交回复
热议问题