对子查询使用ROW_NUMBER()OVER()

时间:2015-10-09 20:49:03

标签: sql-server sql-server-2008

当我的FROM表是子查询时,我需要一些T-SQL脚本来制作ROW_NUMBER OVER()。

它在SQL Server中是禁止的吗?

请参阅下面的示例。

SELECT 
    ROW_NUMBER() OVER(PARTITION BY PATIENTALERT_ID ORDER BY SOURCE_TIME) AS RN 
        FROM (SELECT 
                MIN(PATIENTALERT_SAMPLE_ID) AS PATIENTALERT_SAMPLE_ID, 
                PATIENTALERT_ID, SOURCE_TIME, TEXT 
            FROM 
                PATIENTALERT_SAMPLE
            GROUP BY 
                PATIENTALERT_ID, SOURCE_TIME, TEXT)

错误结果是:

  

消息102,级别15,状态1,行9'''附近的语法不正确。

感谢任何支持

1 个答案:

答案 0 :(得分:5)

问题与您的ROW_NUMBER完全无关。问题是您需要为派生表添加别名:

SELECT 
    ROW_NUMBER() OVER(PARTITION BY PATIENTALERT_ID ORDER BY SOURCE_TIME) AS RN 
        FROM (SELECT 
                MIN(PATIENTALERT_SAMPLE_ID) AS PATIENTALERT_SAMPLE_ID, 
                PATIENTALERT_ID, SOURCE_TIME, TEXT 
            FROM 
                PATIENTALERT_SAMPLE
            GROUP BY 
                PATIENTALERT_ID, SOURCE_TIME, TEXT) AS T;