SQL - 返回上次更新日期

时间:2015-06-28 16:42:23

标签: sql-server

我尝试根据 ParentID 返回 LastUpdateDate 。这个日期可以来自它的任何子表。让我们说有两个子表。孩子一与父母有一对一的关系,孩子两人有多对多的关系。见下面的测试表。任何帮助将不胜感激。

父表

ParentID    Name      LastUpdateDate
1        Parent John     2014-06-26
2        Parent Mark     2004-07-27
3        Parent Bob      2009-04-07
4        Parent Jo       2014-09-26

ChildOne表(1-1关系)

ChildOneID  ParentID    Name            LastUpdateDate
10             1    FirstChild Tom        2011-03-12
20             2    FirstChild David      2014-08-11
30             3    FirstChild Sally      2009-04-06
40             4    FirstChild Jane       2014-11-26

ChildTwo Table(很多很多关系)

ChildTwoID  ParentID    Name            LastUpdateDate
100             1   SecondChild Phil       2014-03-12
200             2   SecondChild Smith      2012-08-10
300             3   SecondChild Paul       1999-04-06
400             4   SecondChild Ed         2010-11-26
500             2   SecondChild Donna      2010-08-10
600             4   SecondChild Melissa    2008-10-16

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

SELECT parent.parentId, MAX(updateTimes.LastUpdateDate) as LastUpdate
FROM parent
INNER JOIN(
        SELECT parentID, LastUpdateDate
        FROM childTable1
        UNION ALL
        SELECT parentID, LastUpdateDate
        FROM childTable2
        -- you may add more tables
        -- you may also filter or group the subqueries
    ) as updateTimes
        ON parent.parentID = updateTimes.parentID
GROUP BY parent.parentId