0

我需要帮助才能执行以下操作:

主表

ID (Primary Key)
DATE_TIME
STATE

子表

ID (Primary Key)
DATE_TIME
LINE1

MainTable.STATE值从 100 变为 200 时,我想选择SubTable.Line1MainTable.DATE_TIME = SubTable.DATE_TIME

似乎LAG()orLEAD()函数可以检测到MainTable.STATE字段中数据的这种转换。

如何使用 SQL 语句使用LAG()LEAD()函数来做到这一点?

感谢所有快速回复。由于 MainTable.STATE 值可以是任何值,因此我不能将其值包含在 sql stmt 中。

4

3 回答 3

0

这应该可以解决问题。

SELECT Line1
FROM SubTable s
INNER JOIN 
(
    SELECT DATE_TIME, State, LAG(State) OVER(ORDER BY DATE_TIME) as LastState
    FROM MainTable 
)
m
ON s.DATE_TIME = m.DATE_TIME
WHERE State = 200
AND LastState = 100
于 2015-06-11T14:29:38.217 回答
0

假设我理解您的问题,您可以执行以下操作:

select Line1
  from (
select T1.[Id] as T1Id,
       T1.[Key] as T1Key,
       T1.[State] as T1State,
       T2.[Id] as T2Id,
       T2.[FKey] as T2Key,
       T2.[Line] as T2Line1,
       lag(T1.[State], 1, 100) OVER (order by T1.[Id]) as PriorState
  from T1
       left outer join T2 on T1.[Key] = T2.FKey
) as Data
 where [T1State] <> PriorState
   and [T1State] = 200
于 2015-06-11T14:35:37.943 回答
0

这是一个解决方案:

SELECT *, CASE WHEN State = 200 AND LAG(State) OVER(ORDER BY ID) = 100 
               THEN (SELECT TOP 1 Line1 FROM SubTable WHERE DATE_TIME = m.DATE_TIME) END 
FROM MainTable m
于 2015-06-11T14:43:10.387 回答