使用sql选择不同的记录

时间:2013-08-01 09:48:43

标签: sql-server

我有一个名为People Job (ID, People ID, Post)的表。

使用样本数据。

ID   People ID      Post

1    P1         Office Assistant

2    P2         Assistant Manager

3    P3         General Manager

4    P1         Officer

5    P2         Manager

我想获得如下记录。

ID    People ID     Post

3    P3          General Manager

4    P1          Officer

5    P2          Manager

3 个答案:

答案 0 :(得分:3)

SELECT PJ.*
FROM People_Job PJ
INNER JOIN (
    SELECT People_ID, MAX(ID) MAX_ID
    FROM People_Job
    GROUP BY People_ID
) T ON PJ.People_ID = T.People_ID AND PJ.ID = T.MAX_ID

答案 1 :(得分:1)

不太确定您的要求,但猜测您想要特定people_id的最高ID数据... 这应该适合:

select * 
from People_Job
where id in (
    select max(id)
    from People_Job
    group by people_id
);

我刚看到GriGrim的帖子 - 如果你在大数据上运行,他的版本应该表现得更好......

答案 2 :(得分:0)

SELECT * FROM `People Job` WHERE `ID People`>2 ORDER BY `ID People`

但是你的表名和列名不应该包含空格。