独特活动的前1名

时间:2014-04-20 07:13:57

标签: sql-server-2008

表名是Events

name    event_id    qty
n1      1           8
n1      2           9
n2      2           25
n3      2           29
n4      2           10
n4      3           11
n3      3           57
n2      3           1
n5      3           2
n1      3           90

我只想为不同的event_id选择前1名。什么是SQL查询?感谢。

1 个答案:

答案 0 :(得分:2)

试试这个:

WITH CTE AS (SELECT *,RN=ROW_NUMBER() OVER(PARTITION BY event_id ORDER BY event_id)
             FROM Events)
SELECT name,event_id,qty FROM CTE WHERE RN=1

结果:

NAME    EVENT_ID    QTY
n1      1           8
n1      2           9  
n4      3           11

请参阅SQL Fiddle中的结果。

修改

对于数量的降序:

WITH CTE AS (SELECT *,RN=ROW_NUMBER() OVER(PARTITION BY event_id ORDER BY event_id)
FROM Events)
SELECT name,event_id,qty FROM CTE WHERE RN=1 ORDER BY QTY DESC

结果:

NAME    EVENT_ID    QTY
n4      3           11
n1      2           9
n1      1           8