如果返回多个匹配项,则只需要第一个匹配项

时间:2014-11-19 13:35:25

标签: sql sql-server

我有一个返回大量记录的SQL脚本。这是代码:

select distinct eb.exerciseindex, eb.exercisestarttime, AVG(pb.playerbirthyear) as Birthavg, COUNT(pb.playerindex) as playersinexercise, pb.playersex from playerbase as pb
inner join exbase as ex on ex.explayerindex = pb.playerindex
inner join exercisebase as eb on eb.exerciseindex = ex.exexerciseindex
where exerciseallowanceindex='B26E10C5-53E1-413A-8A49-A7088D33E690'
and exercise_is_paying='true'
group by exercisestarttime, pb.playersex, eb.exerciseindex 
order by exerciseindex, playersinexercise desc

我附上了一张带有结果的图片。

现在,我想要的是对结果的一种DISTINCT。如果您注意到,在某些情况下,同一EXERCISEINDEX会返回多行(例如,请参阅第1行和第2行)。但我需要的是只返回此exerciseindex的第一行(PLAYERCOUNT更高的那一行)。

任何想法如何做到这一点?

此致

鲍勃

returned sql

2 个答案:

答案 0 :(得分:0)

您可以使用ROW OVER解析函数,如下所示,然后只收集那些Row值为1的行。

ROW_NUMBER() OVER(PARTITION BY exerciseindex ORDER BY exerciseindex) AS Row

对于您的情况,它将是(您可以为此目的使用CTE)

WITH Query1 AS (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY exerciseindex ORDER BY exerciseindex) AS Row
FROM 
(
select distinct eb.exerciseindex, 
eb.exercisestarttime, 
AVG(pb.playerbirthyear) as Birthavg, 
COUNT(pb.playerindex) as playersinexercise, 
pb.playersex from playerbase as pb
inner join exbase as ex on ex.explayerindex = pb.playerindex
inner join exercisebase as eb on eb.exerciseindex = ex.exexerciseindex
where exerciseallowanceindex = 'B26E10C5-53E1-413A-8A49-A7088D33E690'
and exercise_is_paying='true'
group by exercisestarttime, pb.playersex, eb.exerciseindex 
order by exerciseindex, playersinexercise desc
) tab
)
select * from Query1 where Row = 1;

答案 1 :(得分:0)

你应该研究一个名为ROW_NUMBER的简洁的小窗口函数。

使用此功能,您可以执行以下操作:

SELECT * FROM (
    SELECT *, 
        ROW_NUMBER() OVER (PARTITION BY exerciseindex ORDER BY playersinexercise DESC) AS N
    FROM (
        -- your original query goes here - except for the ORDER BY clause --
    ) AS T1
) T2 WHERE T2.N = 1
-- put your ORDER BY clause here --