获取特定列中具有最高值的不同值

时间:2014-11-05 18:52:03

标签: sql oracle distinct

如何在SQL中获取下表中突出显示的行? (突出显示基于具有最高版本的用户名的不同行)

enter image description here

如果您需要纯文本表:

+----+-----------+---+
| 1  | John      | 1 |
+----+-----------+---+
| 2  | Brad      | 1 |
+----+-----------+---+
| 3  | Brad      | 3 |
+----+-----------+---+
| 4  | Brad      | 2 |
+----+-----------+---+
| 5  | Jenny     | 1 |
+----+-----------+---+
| 6  | Jenny     | 2 |
+----+-----------+---+
| 7  | Nick      | 4 |
+----+-----------+---+
| 8  | Nick      | 1 |
+----+-----------+---+
| 9  | Nick      | 3 |
+----+-----------+---+
| 10 | Nick      | 2 |
+----+-----------+---+
| 11 | Chris     | 1 |
+----+-----------+---+
| 12 | Nicole    | 2 |
+----+-----------+---+
| 13 | Nicole    | 1 |
+----+-----------+---+
| 14 | James     | 1 |
+----+-----------+---+
| 15 | Christine | 1 |
+----+-----------+---+

到目前为止我所拥有的(适用于一个用户)

SELECT USER, VERSION 
FROM TABLE 
WHERE USER = 'Brad' 
AND VERSION  = (SELECT MAX(VERSION ) FROM TABLE WHERE USER= 'Brad')

3 个答案:

答案 0 :(得分:4)

SELECT USER, max(VERSION) VERSION
FROM TABLE GROUP BY USER;

如果您需要ID,那么

SELECT ID, USER, VERSION FROM (
    SELECT ID, USER, VERSION, 
           RANK() OVER(PARTITION BY USER ORDER BY VERSION DESC) RNK 
    FROM TABLE
) WHERE RNK = 1;

如果你有

| 2  | Brad      | 5 |
+----+-----------+---+
| 3  | Brad      | 3 |
+----+-----------+---+
| 4  | Brad      | 5 |

使用RANK的查询为您提供了两个用户

| 2  | Brad      | 5 |
+----+-----------+---+
| 4  | Brad      | 5 |

如果您只需要一行,请将RANK()替换为ROW_NUMBER()

在您的查询中,您使用的AND VERSION = (SELECT MAX(VERSION ) FROM TABLE WHERE USER= 'Brad')等同于RANK()(所有行的最大值为VERSION)

答案 1 :(得分:1)

first_value分析函数应该可以解决问题:

SELECT DISTINCT FIRST_VALUE (id) 
                   OVER (PARTITION BY name ORDER BY version DESC)
       name,
       FIRST_VALUE (version) 
                   OVER (PARTITION BY name ORDER BY version DESC)
FROM   my_table

另一种方法是使用row_number函数:

SELECT id, name, version
FROM   (SELECT id, name, version
               ROW_NUMBER() OVER (PARTITION BY name ORDER BY version DESC) rn
        FROM   my_table)
WHERE   rn = 1

不确定我个人喜欢哪个。他们每个人都有自己的优点和丑陋。

答案 2 :(得分:1)

这可能会对您有所帮助:

select id, user, version 
from 
(
   select id, user, version, row_number() over (partition by user order by version desc) rownum
   from yourtable
) as t
where t.rownum = 1    

sql fiddle