2013-04-17 67 views
0

我有兩個表:使用max函數

TotalTimeTable 
(date date,time time) 

FinalListA 
(date date, time time, A int, B int) 

我運行下面的查詢:

SELECT t1.date, 
     t1.time, 
     max(t2.time) 
FROM TotalTimeTable t1, 
    FinalListA t2 
WHERE t2.date=t1.date 
    AND t2.time <= t1.time 
GROUP BY t1.date, 
     t1.time 
ORDER BY t1.date, 
     t1.time 

有沒有辦法從FinalListA拔出A和B,時間=「MAX( t2.time)「在同一個查詢中?

TotalTimeTable:

date  time  
2006-01-01 9:30:01  
2006-01-01 9:30:02 
2006-01-01 9:30:03 
2006-01-01 9:30:04 
2006-01-01 9:30:05 
2006-01-01 9:30:06 

FinalListA:

date  time  A B 
2006-01-01 9:28:01 1 4 
2006-01-01 9:30:02 2 3 
2006-01-01 9:30:04 4 7 
2006-01-01 9:30:07 6 4 
2006-01-01 9:30:10 8 9 
2006-01-01 9:30:11 1 2 

預期的結果是:

date  time  A B 
2006-01-01 9:30:01 1 4 
2006-01-01 9:30:02 2 3 
2006-01-01 9:30:03 2 3 
2006-01-01 9:30:04 4 7 
2006-01-01 9:30:05 4 7 
2006-01-01 9:30:06 4 7 

的時間是從TotalTimeTable FinalListA.time不必在結果。

+2

請提供示例行。 –

回答

0

使用交叉適用於:

SELECT t1.date 
    , t1.time 
    , t2.time 
    , t2.A 
    , t2.B 
FROM TotalTimeTable t1 
CROSS APPLY (
SELECT TOP(1) 
    T2.time 
, T2.A 
, T2.B 
FROM FinalListA t2 
WHERE T2.date = T1.date 
AND T2.time <= t1.time 
ORDER BY T2.time DESC 
) AS T2 
ORDER BY t1.date, 
    t1.time 
+0

對不起,還沒有時間測試它 –

+0

結果是正確的,但它比@techdo –

+0

慢一點這些都是一樣的,但感謝您的投票下來。 – Serge

1

請嘗試:

SELECT t1.date, 
     t1.time, 
     (select top 1 t2.A from FinalListA t2 where t2.date=t1.date and t2.Time<=t1.Time order by t2.Time desc) A, 
     (select top 1 t2.B from FinalListA t2 where t2.date=t1.date and t2.Time<=t1.Time order by t2.Time desc) B 
FROM TotalTimeTable t1 

或使用左加入

select 
    x.date, 
    x.Time, 
    x.A, 
    x.B 
from(
    SELECT t1.*, 
      t2.A, 
      t2.B, 
      ROW_NUMBER() over (PARTITION BY t1.date, t1.time order by t2.time desc) RNum 
    FROM TotalTimeTable t1 left join 
     FinalListA t2 on t1.date=t2.date and t2.Time<=t1.Time 
)x where RNum=1 

或使用CROSS APPLY

SELECT t1.date, 
     t1.time, 
     x.* 
FROM TotalTimeTable t1 cross apply (
SELECT TOP 1 t2.A, t2.B from FinalListA t2 where t2.date=t1.date and t2.Time<=t1.Time order by t2.Time desc)x 
+0

請添加示例數據和預期輸出。 – TechDo

+0

我剛剛添加了示例數據,我將在一分鐘內添加預期輸出 –

+0

請使用子查詢和左連接來檢查編輯後的答案。 – TechDo

0

您可以使用原始查詢作爲約束子查詢(不含ORDER BY)

SELECT t1.Date, t1.Time, t2.Time, t2.A, t2.B 
FROM TotalTimeTable t1 
INNER JOIN 
(
    SELECT t1.date, 
      t1.time, 
      maxt2Time = max(t2.time) 
    FROM TotalTimeTable t1, 
     FinalListA t2 
    WHERE t2.date=t1.date 
     AND t2.time <= t1.time 
    GROUP BY t1.date, 
      t1.time 
) tmax 
ON t1.Date = tmax.date AND t1.Time = tmax.Time 
INNER JOIN FinalListA t2 ON t2.Date = tmax.Date AND t2.Time = tmax.maxt2Time 
+0

@ Serge下面的交叉申請快了大約50% – Ackroydd

+0

是的,這是我打算這樣做的方式,但我想檢查是否有比這更簡單/更快的查詢。 –

+0

可以將子查詢減少爲INNER JOIN(SELECT Date,time = max(time)from FinalListA GROUP BY date)tmax – Ackroydd