我有一个包含LocationId字段的表。在某些情况下,如果记录共享相同的外键,则LocationId可能会以-1开始。
我想要做的是在我的选择查询中就是发生这种情况,即之前的位置。
示例数据:
Record FK StartTime EndTime Location
1 110 2011/01/01 12.30 2011/01/01 6.10 456
2 110 2011/01/01 3.40 2011/01/01 4.00 -1
3 110 2011/01/02 1.00 2011/01/02 8.00 891
4 110 2011/01/02 5.00 2011/01/02 6.00 -1
5 110 2011/01/02 6.10 2011/01/02 6.30 -1
对于记录2,-1应该是456,对于记录4和5
,应该是891答案 0 :(得分:2)
对于整个结果集
with tmp(Record ,FK ,StartTime ,EndTime ,Location)
as( select
1, 110 ,'2011/01/01 12:30', '2011/01/01 6:10', 456 union all select
2, 110 ,'2011/01/01 3:40', '2011/01/01 4:00', -1 union all select
3, 110 ,'2011/01/02 1:00', '2011/01/02 8:00', 891 union all select
4, 110 ,'2011/01/02 5:00', '2011/01/02 6:00', -1 union all select
5, 110 ,'2011/01/02 6:10', '2011/01/02 6:30', -1
)
-- ignore above this line
select curr.Record, curr.FK, curr.StartTime, curr.EndTime,
case when curr.Location=-1 then prev.Location else curr.Location end Location
from tmp curr
outer apply
(select top 1 prev.location
from tmp prev
where curr.location=-1 and prev.FK=curr.FK
and prev.starttime < curr.starttime
and prev.location <> -1
order by prev.starttime desc) prev
答案 1 :(得分:2)
如果当前行中的位置值为-1,则此版本仅产生查找成本。在查询计划中,左连接包含一个传递谓词,如果位置&lt;&gt;,则跳过谓词运行连接的内侧。 -1
;
WITH CTE
AS (
SELECT *
FROM (
VALUES
(1, 110 ,'2011/01/01 12:30', '2011/01/01 6:10', 456),
(2, 110 ,'2011/01/01 3:40', '2011/01/01 4:00', -1),
(3, 110 ,'2011/01/02 1:00', '2011/01/02 8:00', 89),
(4, 110 ,'2011/01/02 5:00', '2011/01/02 6:00', -1),
(5, 110 ,'2011/01/02 6:10', '2011/01/02 6:30', -1)
) V (record, fk, start_time, end_time, location)
)
SELECT T1.record,
T1.fk,
T1.start_time,
T1.end_time,
CASE WHEN T1.location != -1 THEN Location
ELSE
(
SELECT TOP (1)
T2.location
FROM CTE AS T2
WHERE T2.record < T1.record
AND T2.fk = T1.fk
AND T2.location != -1
ORDER BY T2.Record DESC
)
END
FROM CTE AS T1
;
答案 2 :(得分:1)
您可以使用相关子查询。例如:
SELECT *
, (SELECT TOP 1 Location
FROM MyTable T2
WHERE T2.Record <= T1.Record
AND T2.FK = T1.FK
AND T2.Location <> -1
ORDER BY T2.Record DESC) AS BestLocation
FROM MyTable T1
答案 3 :(得分:1)
SELECT
Record,
FK,
StartTime,
EndTime,
(
SELECT
Location
FROM
MyTable
WHERE
Record =
(
SELECT
MAX(Record)
FROM
MyTable t2
WHERE
t2.Record =< t1.Record AND
Location >= 0
)
)
FROM
MyTable t1