根据列的最高值和另一列的条件获取行

时间:2012-08-31 02:06:22

标签: sql database sql-server-2008 tsql self-join

我正在寻找一个SQL查询,它为每个用户提供一个Scr,从最高的Seq开始,Scr不等于0.保证每个用户的Seq值都是唯一的。

示例数据:

ID  Cde User    Scr Seq
1   1   James   110 19
2   1   James   85  20
3   1   James   99  21
4   1   James   99  22
5   1   James   0   23
6   2   Andrew  88  19
7   2   Andrew  88  20
8   2   Andrew  88  21
9   2   Andrew  0   22
10  2   Andrew  0   23
11  3   David   0   19
12  3   David   95  20
13  3   David   95  21
14  3   David   0   22
15  3   David   0   23

查询结果:

ID  Cde User    Scr Seq
4   1   James   99  22
8   2   Andrew  88  21
13  3   David   95  21

4 个答案:

答案 0 :(得分:1)

您可以在子查询中找到最大的seq

SELECT  a.*
FROM    tableName a INNER JOIN
        (
            SELECT [user], max(seq) MaxSeq
            FROM tablename
            WHERE Scr <> 0
            Group By [user]
        ) b 
            ON a.[user] = b.[user] AND
               a.seq = b.maxSeq
ORDER BY ID

SQLFiddle Demo

答案 1 :(得分:1)

使用row_number()函数,您可以识别具有此条件的行,其中score不为0,并按seq按降序排序:

select ID, Cde, User, Scr, Seq
from (select t.*,
             row_number() over (partition by user order by seq desc) as seqnum
      from t
      where scr <> 0
     ) t
where seqnum = 1

(我假设“scr”是得分。)

答案 2 :(得分:1)

Declare @t table([ID] int, [Cde] int, [User] varchar(6), [Scr] int, [Seq] int);

INSERT INTO @t([ID], [Cde], [User], [Scr], [Seq])
VALUES
    (1, 1, 'James', 110, 19),
    (2, 1, 'James', 85, 20),
    (3, 1, 'James', 99, 21),
    (4, 1, 'James', 99, 22),
    (5, 1, 'James', 0, 23),
    (6, 2, 'Andrew', 88, 19),
    (7, 2, 'Andrew', 88, 20),
    (8, 2, 'Andrew', 88, 21),
    (9, 2, 'Andrew', 0, 22),
    (10, 2, 'Andrew', 0, 23),
    (11, 3, 'David', 0, 19),
    (12, 3, 'David', 95, 20),
    (13, 3, 'David', 95, 21),
    (14, 3, 'David', 0, 22),
    (15, 3, 'David', 0, 23);

Select [ID], [Cde], [User], [Scr], [Seq] From 
(Select Rn = Row_Number()Over(Partition By [User] Order By Seq Desc,[User]) , *
From @t 
Where Scr <> 0) x Where x.Rn = 1 Order By 5 Desc,3

答案 3 :(得分:0)

您不需要自我加入。您可以使用row_number功能为每个用户选择最高seq

select ID, Cde, User, Scr, Seq from  (
   select *, row_number() over (partition by Cde order by Seq desc) rownum
   from tableName where scr <> 0
) a
where a.rownum=1

这必须使用内部查询来完成,因为row_number()仅在select中有效,而不在where中。