将外部表字段连接到子查询

时间:2014-02-10 17:52:14

标签: sql sql-server-2008 join

假设我有一个表tblNumbers,其中包含四个字段fldIndexfldNumber以及两个fldLink1fldLink2的加入字段。我需要添加给定索引的fldNumber和给定索引的fldNumber + 1.我尝试了如下但不确定如何正确指定内部表中的where子句...

SELECT T2.fldNum + T1.fldNumHalf AS fldNum
FROM tblNumbers AS T2 INNER JOIN (SELECT fldNum/2 AS fldNumHalf
                            FROM tblNumbers
                            WHERE fldIndex = T2.fldIndex + 1) T1 ON
tblNumbers.fldLink1 = T1.fldLink1 AND tblNumbers.fldLink2 = T1.fldLink2

我现在拥有它的方式不起作用,有人能告诉我哪里出错了吗?

Sample Data...
fldLink1   fldLink2   fldNum   fldIndex
2400       5          1.53     0
2400       5          2        1
2400       5          3.53     2
2400       5          4.25     3
2400       5          4.86     4
2400       5          5        5
2400       5          6        6
2400       5          7        7

tblNumbers.fldNum would be...
4.25

T1.fldNumHalf would be...
4.86  

The final field value would be...
6.68

2 个答案:

答案 0 :(得分:1)

在这种情况下,您不需要子查询,只需要常规连接:

SELECT 
    t2.fldnum t2f,t3.fldnum t3f,
    T2.fldNum + T3.fldnum/2 AS fldNum
FROM 
    tblNumbers AS t2
    INNER JOIN tblNumbers AS t3
    ON t2.fldIndex+1=t3.fldIndex
        AND t2.fldLink1=t3.fldLink1
        AND t2.fldLink2=t3.fldLink2

SQLFiddle here

答案 1 :(得分:0)

听起来我想要添加连续的行。我不知道“一半”来自哪里。我也不明白为什么你关心前两列:

SELECT (T2.fldNum + T1.fldNum) / 2 AS fldNum
FROM tblNumbers T1 INNER JOIN 
     tblNumbers T2
     on T2.FieldIndex = t1.FieldIndex + 1
WHERE t1.FieldIndex = 3;