假设您在每个表中都有一个 created_datetime 列来指定最近的行,我们可以使用 RowNumber 函数来完成这项工作,请参见此示例
declare @ACCOUNTS table (ID_ACC int)
declare @EMAILS table (EMAIL VARCHAR(50), ID_ACC int, CREATED_DATETIME DATETIME)
declare @PHONES table (PHONE VARCHAR(50), ID_ACC int, CREATED_DATETIME DATETIME)
insert into @ACCOUNTS
SELECT '1' ID_ACC
UNION ALL
SELECT '2' ID_ACC
UNION ALL
SELECT '3' ID_ACC
INSERT INTO @EMAILS
SELECT 'MyEmail@test.com' EMAIL,'1' ID_ACC, '2015-12-14 22:00:00' CREATED_DATETIME
UNION ALL
SELECT 'MyNewemail@test.com' EMAIL,'1' ID_ACC, '2015-12-14 22:53:00'
UNION ALL
SELECT '3rdemail@test.com' EMAIL,'3' ID_ACC, '2015-12-14 22:54:00'
UNION ALL
SELECT 'NEW3rdemail@test.com' EMAIL,'3' ID_ACC, '2015-12-14 22:55:30'
INSERT INTO @PHONES
SELECT '00213555555' PHONE,'1' ID_ACC, '2015-12-14 22:10:00' CREATED_DATETIME
UNION ALL
SELECT '00213554444' PHONES,'2' ID_ACC, '2015-12-14 22:54:00'
UNION ALL
SELECT '00213556666' PHONES,'3' ID_ACC, '2015-12-14 22:54:00'
UNION ALL
SELECT '00213557777' PHONES,'3' ID_ACC, '2015-12-14 23:10:00'
SELECT
*
FROM
(SELECT
ROW_NUMBER () over (partition by A.ID_ACC order by E.CREATED_DATETIME DESC,P.CREATED_DATETIME DESC) AS ROW_ORDER,
A.ID_ACC,
E.EMAIL,
P.PHONE
FROM @ACCOUNTS as A
left join @EMAILS as E
on A.ID_ACC=E.ID_ACC
left join @PHONES as P
on A.ID_ACC=P.ID_ACC) AS TAB
WHERE TAB.ROW_ORDER=1