获取重复ID的MAX()

时间:2015-05-14 20:16:09

标签: sql sql-server

这是我的查询结果当前的样子。如何获取每个唯一ID的MAX()值?

IE,

for 5267139 is 8.
for 5267145 is 4

5267136 5
5267137 8
5267137 2
5267139 8
5267139 5
5267139 3
5267141 4
5267141 3
5267145 4
5267145 3
5267146 1
5267147 2
5267152 3
5267153 3
5267155 8


    SELECT DISTINCT st.ScoreID, st.ScoreTrackingTypeID
    FROM ScoreTrackingType stt
    LEFT JOIN ScoreTracking st
    ON stt.ScoreTrackingTypeID = st.ScoreTrackingTypeID
    ORDER BY st.ScoreID, st.ScoreTrackingTypeID DESC 

Results

1 个答案:

答案 0 :(得分:4)

GROUP BY会根据您指定的列将您的表分区为单独的块。然后,您可以对每个块应用聚合函数(在这种情况下为MAX) - 默认情况下,此行为适用于以下语法:

SELECT First_column, MAX(Second_column) AS Max_second_column
FROM Table
GROUP BY First_column

编辑:根据上面的查询,看起来你根本不需要ScoreTrackingType表,但保留它,你可以使用:

SELECT st.ScoreID, MAX(st.ScoreTrackingTypeID) AS ScoreTrackingTypeID
FROM ScoreTrackingType stt
    LEFT JOIN ScoreTracking st ON stt.ScoreTrackingTypeID = st.ScoreTrackingTypeID
GROUP BY st.ScoreID
ORDER BY st.ScoreID

GROUP BY将无需DISTINCTMAX将为您提供所需的价值,ORDER BY仍将适用,但由于会有每个ScoreTrackingTypeID只能有一个ScoreID值,您可以将其从排序中删除。