LEFT OUTER JOIN(SELECT * FROM TABLE)可能吗?

时间:2013-05-17 23:12:36

标签: sql-server tsql

我有两张表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

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

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

1 个答案:

答案 0 :(得分:4)

首先,我会按人和日期对CTE和ROW_NUMBER()函数对工资进行排名。这会将最近的工资按人数降序排列在第一个位置,我们可以稍后过滤(排名= 1)。之后,从LEFT JOIN到别名的CTE变为简单的Person

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约束。