从2桌和2人获取最近的约会

时间:2017-04-19 13:49:07

标签: sql sql-server tsql

我有桌子:

   Person
-------------
ID | name

           Notes
---------------------------
targetID | Content | Date

      CallHistory
--------------------------
CallerID | CalleeID | Date

现在说我有一个人和一个配偶(在同一个人表上)。 他们有相应的笔记和呼唤史。

我想要的是从配偶或个人的最近日期(电话或备注)中选择最近的日期

我试过了:

SELECT top 1 Date, ID from (select TargetID as ID, Date from notes
                        union
                       SELECT CalleeID as ID, Date from Callhistory)
WHERE ID in (person.ID, spouse.ID)

但没有运气。

编辑: 此选择位于select语句中:

select p.*, SELECT top 1 Date, ID from (select TargetID as ID, Date from notes
                            union
                           SELECT CalleeID as ID, Date from Callhistory)
    WHERE ID in (person.ID, spouse.ID) as RecentContactDate
From Person person
LEFT JOIN PersonRelationship pr on person.ID = pr.ID AND pr.Type = 3 -- spouse
LEFT JOIN Person spouse on pr.RelatedID = spouse.ID
......

我收到Ambigous column name Date错误。

任何想法?

1 个答案:

答案 0 :(得分:0)

@Sven在这篇文章中的答案帮助我解决了我的问题:SQL MAX of multiple columns?

我所做的就是将两个人的两张桌子加入一排(需要为每个人的桌子获取MAX日期 - CallHistory和Notes)。然后从这四列中取出MAX。所以这是修复:

select p.*,
(SELECT Max(v) 
   FROM (VALUES (pNote.Date), (pCh.Date), (sNote.Date),(sCh.Date)) AS value(v)) as [MaxDate]
    WHERE ID in (person.ID, spouse.ID) as RecentContactDate
From Person person
LEFT JOIN PersonRelationship pr on person.ID = pr.ID AND pr.Type = 3 -- spouse
LEFT JOIN Person spouse on pr.RelatedID = spouse.ID
LEFT JOIN (SELECT ID, MAX(Date) from Notes) pNote on pNote.targetID = person.ID
LEFT JOIN (SELECT ID, MAX(Date) from CallHistory) pCh on person.ID = ch.CalleeID
LEFT JOIN (SELECT ID, MAX(Date) from Notes) sNote on spouse.ID = pNote.targetID
LEFT JOIN (SELECT ID, MAX(Date) from CallHistory) sCh on spouse.ID = ch.CalleeID

我希望这将有助于将来的任何人。