带有PIVOT的列名MSSQL 2008无效

时间:2015-01-27 13:51:30

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

我正在制作一些应用程序,我需要存储过程中的一些行。我需要将它们插入到Datatable中。所以这是我的疑问:

    WITH OrderedResults AS ( select ROW_NUMBER() OVER (ORDER BY tert) AS 'RowNumber', tert, kert, ktgszalsz,szlasz, szlanev from dbo.[func_karton]('','5000','99999999999','0','99999999999','1','99999999999','2014-01-01','2014-01-31') where ktgszalsz in (61,611,6211,6311,6411,6511,6611,6711,6811) union select ROW_NUMBER() OVER (ORDER BY tert) AS 'RowNumber', tert, kert, '0' AS ktgszalsz,szlasz, szlanev from dbo.[func_karton]('','5000','99999999999','0','99999999999','1','99999999999','2014-01-01','2014-01-31') where ktgszalsz not in (61,611,6211,6311,6411,6511,6611,6711,6811)) 
SELECT ROW_NUMBER() OVER (ORDER BY a61) AS 'Row',* FROM (
    SELECT * FROM ( 
        SELECT LTRIM(szlanev) as 'name',('a'+ktgszalsz) as ktgszalsz, SUM(tert)- sum(kert) as 'value' FROM OrderedResults group by ktgszalsz,szlanev
    ) a
    pivot( 
        max(value) for ktgszalsz in (a0,a61,a611,a6211,a6311,a6411,a6511,a6611,a6711,a6811)
    ) piv 
)as b WHERE Row BETWEEN 1 AND 5

当我运行它时,我收到此错误消息:

Error: Invalid column name 'Row'

但是当我在没有WHERE条件的情况下运行它时,我有一个“行”列。

1 个答案:

答案 0 :(得分:1)

您可以'在WHERE子句中使用别名,因此请使用以下命令:

SELECT * FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY a61) AS [Row] <...>
) WHERE [Row] BETWEEN 1 AND 5