SQL连接.一对多关系

J S*_*osh 5 sql sql-server

我有两张桌子如下

Table 1
-----------------------------------
UserID   | UserName | Age | Salary
-----------------------------------
1        | foo      | 22  | 33000       
-----------------------------------
Table 2
------------------------------------------------
UserID   | Age      | Salary     | CreatedDate
------------------------------------------------
1        | NULL     | 35000      | 2015-01-01
------------------------------------------------
1        |  28      | NULL       | 2015-02-01
------------------------------------------------
1        |  NULL    | 28000      | 2015-03-01
------------------------------------------------

我需要这样的结果.

Result
-----------------------------------
UserID   | UserName | Age | Salary
-----------------------------------
1        | foo      | 28  | 28000
-----------------------------------

这只是一个例子.在我的真实项目中,我在上表中有大约6列,如Age和Salary.

在表2中,每条记录只有一个值,即如果Age有值,则Salary将为NULL,反之亦然.

更新:

表2包含CreatedDate列.所以我想获得最新的"NOTNULL"CELL值而不是最大值.

lc.*_*lc. 3

注意:我假设您知道自己在做什么,但您只是没有告诉我们有关您的架构的所有信息。

它看起来Table 2实际上是一个“更新”表,其中每一行都包含要应用于 中的基本实体的更改增量Table 1。在这种情况下,您可以使用相关联接(技术上是外部应用)检索每列的数据并将结果放在一起。像下面这样:

select a.UserID, a.UserName, 
    coalesce(aAge.Age, a.Age),
    coalesce(aSalary.Salary, a.Salary)
from [Table 1] a
outer apply (
    select Age
    from [Table 2] x
    where x.UserID = a.UserID 
    and x.Age is not null
    and not exists (
        select 1
        from [Table 2] y
        where x.UserID = y.UserID
        and y.Id > x.Id
        and y.Age is not null
    )
) aAge,
outer apply (
    select Salary
    from [Table 2] x
    where x.UserID = a.UserID 
    and x.Salary is not null
    and not exists (
        select 1
        from [Table 2] y
        where x.UserID = y.UserID
        and y.Id > x.Id
        and y.Salary is not null
    )
) aSalary
Run Code Online (Sandbox Code Playgroud)

请注意,我假设您至少有一IdTable 2随着每次插入而单调增加。如果您有“更改时间”列,请使用它来获取最新行,因为它更好。