0

我有两张桌子:

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

有没有办法从同一个查询中 time = "max(t2.time)" 的 FinalListA 中提取 A 和 B?

总时间表:

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

最终名单A:

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 不必在结果中。

4

3 回答 3

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

或使用交叉应用

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
于 2013-04-17T09:54:39.497 回答
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
于 2013-04-17T10:03:06.190 回答
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
于 2013-04-17T10:23:13.537 回答