选择多个列,其中一列最大,另一列不同

时间:2016-05-21 20:30:06

标签: sql greatest-n-per-group

所以我想选择具有不同contractNo和max versionNo。

的所有记录

所以我有一张这样的表:

| username | contractNo | versionNo |
|===================================|
| lucian   |     1      |     1     |
| john     |     2      |     1     |
| lucian   |     2      |     1     |
| kris     |     3      |     1     |
| lucian   |     1      |     2     |
| david    |     4      |     1     |
| lucian   |     1      |     4     |
| adam     |     5      |     1     |
| lucian   |     2      |     2     |
| kris     |     3      |     2     |
| lucian   |     3      |     1     |
| lucian   |     1      |     3     |
| lucian   |     1      |     5     |
| lucian   |     4      |     1     |

我要选择以下记录:

| username | contractNo | versionNo |
|===================================|
| lucian   |     1      |     5     |
| lucian   |     2      |     2     |
| lucian   |     3      |     1     |
| lucian   |     4      |     1     |

我有这个查询,但这只是按contractNo和versionNo排序的降序返回它们。

SELECT username, contractNo, versionNo 

FROM contracts 

WHERE useremail = 'lucian'

order by contractNo, versionNo desc;

我相信我需要做某种加入,但我不确定如何。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

这应该有效:

SELECT
    username
    ,contractNo
    ,MAX(versionNo) AS versionNo
FROM contracts
WHERE username = 'lucian'
GROUP BY
    username
    ,contractNo
ORDER BY contractNo ASC

享受。

答案 1 :(得分:0)

使用子句subselect和group by

SELECT username, contractNo, versionNo 
FROM contracts 
where  (username, contractNo, versionNo) in 
        (select username, contractNo, max(versionNo) 
            from contracts group by username, contractNo )
and username = 'lucian';