SQL查询奇怪的结果?

时间:2012-06-08 11:50:21

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

我有以下SQL查询。我删除了内部工作但显示了结果的黑盒效果。

整个查询不会返回{0,10,5,-2,10},而是返回{0,0,0,0,0}而我无法理解为什么逐行分区正在影响它???

如果我排除WHERE rn = 1条件,它就能正常工作。因此,由于某种原因,行号未被正确查看。

我认为问题特定于值{0,10,5,-2,10},无论出于何种原因,因为当我用不同的参数调用此函数时,值会返回正常。

SELECT  Col1, isnull(Col2,0) AS Col11, isnull(Col4,0) AS Col4, isnull(q.Col3,0) AS Col3, isnull(q.Col5,0) AS Col5
FROM    
(
    SELECT * , ROW_NUMBER() OVER (PARTITION BY Col1 ORDER BY Col5 ASC, Col3 ASC) rn
    FROM 

    (SELECT 0 AS  Col1, tab34.Col2, tab34.Col4, tab34.Col3, Col5 FROM
            (SELECT PST FROM Func2('x','y')) tab3
        LEFT JOIN

            (SELECT Col2, Col4,Col3,abs(tab33.Value + Col6) AS Value, Col7 AS Col5 FROM

                (SELECT tab11.Col2, tab11.Col4, tab11.Col3, Value FROM
                    (SELECT Col2, Col4, Col3 FROM Table2 WHERE Col8 = 'y' AND Col10 = 1) tab22
                JOIN
                    (SELECT Col2, sum(Value) AS Value, Col4, Col3 FROM Table1 WHERE Col9 = 'x' AND Col8 = 'y' GROUP BY Col2, Col4, Col3) tab11
                ON tab11.Col2 = tab22.Col2 AND tab11.Col4 = tab22.Col4 AND tab11.Col3 = tab22.Col3
                WHERE Value < 0) tab33

            JOIN
                (SELECT Col11, Col6, Col7 FROM dbo.Func1('x','y')) Shifts
            ON Shifts.Col11 = tab33.Col2) tab34 

        ON tab3.PST = tab34.Value
    ) VolData
) q
WHERE   rn = 1

1 个答案:

答案 0 :(得分:0)

这可能是一个愚蠢的答案,请原谅。

行号是否为零?如果将where子句更改为:

会发生什么
WHERE rn = 0

编辑:我也注意到该行中可能缺少“AS”:

SELECT * , ROW_NUMBER() OVER (PARTITION BY Col1 ORDER BY Col5 ASC, Col3 ASC) rn

应该是:

SELECT * , ROW_NUMBER() OVER (PARTITION BY Col1 ORDER BY Col5 ASC, Col3 ASC) AS rn