假設你在每個表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 '[email protected]' EMAIL,'1' ID_ACC, '2015-12-14 22:00:00' CREATED_DATETIME
UNION ALL
SELECT '[email protected]' EMAIL,'1' ID_ACC, '2015-12-14 22:53:00'
UNION ALL
SELECT '[email protected]' EMAIL,'3' ID_ACC, '2015-12-14 22:54:00'
UNION ALL
SELECT '[email protected]' 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
1)標籤所使用的數據庫管理系統(我猜應該是sql server)2)發佈一些示例數據3)發佈您的嘗試到目前爲止 –
正如@vkp所說,更多的數據將會有用。據說,根據我的經驗,加入窗口函數比外部函數更快,應該返回空值。 –
感謝您的反饋!將更新您的建議。乾杯,N – nbardach