使用最大功能

时间:2013-04-17 09:52:35

标签: sql sql-server sql-server-2008

我有两张桌子:

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,其中time =“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不必在结果中。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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