3表中的详细信息列不断更新 我想获取最新的lastUpdateTime 给定的日期时间 其中ID与3表匹配
tblClient
ID, AddressDetail, lastUpdateTime
789 Address '2013-09-27 00:00:00:000'
789 Address '2013-09-23 00:00:00:000'
897 Address '2013-09-22 00:00:00:000'
354 Address '2013-09-28 00:00:00:000'
tblOrder
ID, OrdersDetail, lastUpdateTime
789 Order '2013-09-26 00:00:00:000'
897 Order '2013-09-30 00:00:00:000'
897 Order '2013-09-27 00:00:00:000'
354 Order '2013-09-30 00:00:00:000'
tblAccount
ID, AccountDetail, lastUpdateTime
789 Detail '2013-09-23 00:00:00:000'
897 Detail '2013-09-25 00:00:00:000'
354 Detail '2013-09-28 00:00:00:000'
- 这不会这样做
SELECT a.ID,a.AccountDetail,max(A.lastUpdateTime)
From tblClient A
left join tblOrder B
on A.ID = B.ID
left join tblAccount C
on C.ID = A.ID
where A.LastUpdateTime between '2013-09-20 00:00:00:000' and '2013-09-30 00:00:00:000'
答案 0 :(得分:0)
使用UNION
而不是JOIN
,订购结果然后为每个ID取第一行:
SELECT ID, detail, LastUpdateTime
FROM (
SELECT ID, detail, LastUpdateTime,
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY LastUpdateTime desc) rownum
FROM (
SELECT ID, AddressDetail as detail, lastUpdateTime
From tblClient
WHERE LastUpdateTime between '2013-09-20 00:00:00:000' and '2013-09-30 00:00:00:000'
UNION
SELECT ID, orderDetail, lastUpdateTime
From tblOrder
WHERE LastUpdateTime between '2013-09-20 00:00:00:000' and '2013-09-30 00:00:00:000'
UNION
SELECT ID, AccountDetail, lastUpdateTime
From tblAccount
WHERE LastUpdateTime between '2013-09-20 00:00:00:000' and '2013-09-30 00:00:00:000'
) x
) y
WHERE rownum = 1
请参阅SQLFiddle
这样做的另一个好处是还会返回最新行的详细信息列。