加入派生表本身

时间:2011-07-04 08:19:15

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

简而言之:

我有事件表: [TBL]

time | newState
1200 | 1
1300 | 2
1400 | 5

我需要将此表转换为区间表[interval]:

t0   | t1   | state
1200 | 1300 | 1
1300 | 1400 | 2

限制:SQL紧凑版

查询:

SELECT leftPart.time AS t0, min(rightPart.time) AS t1, leftPart.newState
FROM tbl AS leftPart 
LEFT OUTER JOIN tbl As rightPart
ON leftPart.time<rightPart.time
GROUP BY leftPart.Time,leftPart.newState

当[tbl]是数据库中的永久表时它很完美,但在我的情况下[tbl]是从另一个select子查询派生的!像这样:

(SELECT time,newState
from ...) AS derivedTb

所以,当我尝试这样的事情时:

SELECT derivedTbl.time As t0,derivedTbl.state,min(rigthTblPart.time) FROM
(SELECT time,newState
from ...) AS derivedTbl
LEFT OUTER JOIN with derivedTbl AS rigthTblPart
ON derivedTbl.Time<rightTblPart.Time ...

它抛出错误:“derivedTbl不存在”......

似乎在它的别名下的派生表对于更高级别的查询是不可见的(谢谢,谷歌翻译!))...

有没有办法在查询中存储派生表并在查询的不同部分使用它们? SQL CE不支持临时表,视图和公用表表达式......

任务详情(如果有趣): 我有2个事件表:

[states1]
time | state1
1200 | 1
1300 | 2
1400 | 3

[states2]
time | state2
1200 | 0
1230 | 10
1330 | 20
1430 | 30

我需要在间隔表中转换它们:

[intervals]
t0      t1      state1  state2
1200    1230    1   0
1230    1300    1   10
1300    1330    2   10
1330    1400    2   20
1400    1430    3   20
1430    NULL    3   30

转换阶段: 1.总体时间表

(SELECT Time FROM States1 
UNION
SELECT Time FROM States2) AS timetbl
  1. 加入states1 table
  2. 加入states2 table
  3. 这一刻一切顺利:

    SELECT     states12tbl.time, states12tbl.state1, states2tbl.State AS state2
       FROM          (SELECT     states12tbl_1.time, states12tbl_1.state1, MAX(states2tbl.Time) AS states2time
           FROM          (SELECT     timetbl.time, states1tbl.State AS state1
               FROM          (SELECT     timetbl_1.Time AS time, MAX(States1tbl.Time) AS state1time
                   FROM          (SELECT     Time
                       FROM          States1
                       UNION
                       SELECT     Time
                       FROM         States2) AS timetbl_1 LEFT OUTER JOIN
                      States1 AS States1tbl ON States1tbl.Time <= timetbl_1.Time
                   GROUP BY timetbl_1.Time) AS timetbl INNER JOIN
                  States1 AS states1tbl ON timetbl.state1time = states1tbl.Time
    
    1. 自己加入表...这里有问题,我需要自己加入代码(3),因为sql ce不能记住临时表...如果你有更好的想法,请分享:)

2 个答案:

答案 0 :(得分:0)

根据您的第一个SELECT创建一个VIEW。

答案 1 :(得分:-1)

Onotole,我认为这个WITH正在制造麻烦。

重写此查询,如

SELECT 
    derivedTbl.time As t0,
    derivedTbl.state,
    min(rigthTblPart.time) 
FROM
   (SELECT time,newState from ...) AS derivedTbl
   LEFT OUTER JOIN derivedTbl AS rigthTblPart
       ON derivedTbl.Time<rightTblPart.Time 
....