1

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'
4

1 回答 1

0

使用 aUNION而不是 a 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

这也有一个优点,即最新行的详细信息列也被返回。

于 2013-09-24T01:18:28.767 回答