SQL Server查询输出

时间:2015-04-16 10:59:50

标签: sql sql-server

我有一张像这样的人物记录表:

Tableid PeopleID DeptID StartMonth StartYear
--------------------------------------------
  1       101        1       3        2014
  2       101        2       2        2015
  3       102        2       5        2015
  4       102        5       4        2013
  5       103        6       8        2015
  6       103        7       9        2015

我只希望每个peopleid的最新工作历史与相应的tableid,这意味着我希望得到以下输出:

tableid  peopleid  
2        101
3        102
6        103

此处我在输出中仅需要tableidpeopleid

4 个答案:

答案 0 :(得分:1)

您可以将ROW_NUMBER()PARTITION BY一起使用。这样的事情。

CREATE TABLE People 
(
    Tableid INT,
    PeopleID INT,
    DeptID INT,
    StartMonth INT,
    StartYear INT
)

INSERT INTO People
    SELECT  1,       101,        1,      3,         2014
    UNION ALL SELECT  2,       101,        2,      2,         2015
    UNION ALL SELECT  3,       102,        2,       5,        2015
    UNION ALL SELECT  4,       102,        5,       4,       2013
    UNION ALL SELECT  5,       103,        6,       8,        2015
    UNION ALL SELECT  6,       103,        7,       9,        2015

;WITH CTE as 
( 
    SELECT Tableid,PeopleID,ROW_NUMBER()OVER(PARTITION BY PeopleID ORDER BY StartYear DESC,StartMonth DESC) r
    FROM People
)
SELECT Tableid, PeopleID FROM CTE
WHERE r = 1

答案 1 :(得分:1)

使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by peopleid
                                order by startyear desc, startmonth desc
                               ) as seqnum
      from table t
     ) t
where seqnum = 1;

答案 2 :(得分:1)

这是一个不使用row_number()的解决方案,因此可以在2005年之前使用SQL Server版本:

SELECT Tableid, PeopleID 
FROM People t_outer 
WHERE Tableid = (SELECT TOP 1 Tableid FROM MyTable t_inner WHERE t_inner.PeopleID = t_outer.PeopleID ORDER BY StartYear DESC, StartMonth DESC)

答案 3 :(得分:0)

SELECT *
FROM table t
WHERE NOT EXISTS ( SELECT 'a'
                   FROM table t2
                   WHERE t2.PeopleID = t.PeopleID 
                   AND t2.StartYear * 100 + t2.StartMonth > t.StartYear * 100 + t.StartMonth
                  )