5

我有两张桌子PersonSalary.

Person

PersonId   |  Name   |   Surname
--------------------------------
       1      John          Deer
       2      Mark          Bear

Salary

SId | PersonId | Date                       | Salary
----------------------------------------------------
1            2   2013-01-01 00:00:00.000      100
2            2   2012-01-01 00:00:00.000      90
3            2   2011-01-01 00:00:00.000      80

我想做的是,如果一个人有工资记录,那么它应该在结果中显示最新的工资信息,如果没有工资记录,那么它应该将工资信息显示为空,就像......

Result
------------------------------------------------------------------------
PersonId   |   Name   | Surname  |  Date                      |  Salary
       1       John        Deer     NULL                            NULL
       2       Mark        Bear     2013-01-01 00:00:00.000         100

我知道它必须是这样的,但由于缺乏知识,我无法实现..

SELECT 
    P.PersonId, P.Name, P.Surname, SL.Date, SL.Salary
FROM 
    PERSON P
LEFT OUTER JOIN 
    (SELECT TOP 1 S.PersonId, S.Date, S.Salary 
     FROM Salary 
     WHERE S.PersonId = P.PersonId ORDER BY Date DESC) SL
4

1 回答 1

4

ROW_NUMBER()我将首先使用 CTE 和函数按人员和日期对薪水进行排名。这将按人最近的薪水按降序排列在第一位,我们可以稍后过滤(其中 rank = 1)。之后,它变成了一个简单LEFT JOIN的 fromPerson到别名 CTE:

WITH RankedSalaries AS
(
    SELECT 
        PersonId
        ,Date
        ,Salary
        ,ROW_NUMBER() OVER (PARTITION BY PersonId ORDER BY Date DESC) AS RowNum
    FROM 
        Salary
)
SELECT 
    p.PersonId
    ,p.Name
    ,p.Surname
    ,s.Date
    ,s.Salary
FROM
    Person p
LEFT JOIN
    RankedSalaries s
    ON
    p.PersonId = s.PersonId
WHERE
    s.RowNum = 1

或者,您可以获取 CTE 的内容并将其移动到您开始的查询的括号之间(即LEFT JOIN (<CTE query>))。只记得添加= 1约束。

于 2013-05-17T23:16:47.690 回答