4

我一定做错了什么。我正在尝试使用 row_number 函数仅选择 rownum 为1的值,以便始终获得最新的index。但是 where 子句中无法识别 rownum。

SELECT  fs.docu_id as docID 
, fs.field_3 AS ProductNo
, fs.field_4 AS [Status]
, fs.field_5 AS [Index]
,pd.[doku_nr] AS docIDshort
, ROW_NUMBER() OVER(PARTITION BY fs.field_3 ORDER BY fs.field_5 Desc) AS rownum
FROM [table1] fs
JOIN [table2] pd
ON fs.docu_id=pd.docu_id 
AND  fs.field_4 = 'valid'

我错过了什么?我需要创建不同的选择 stmt 吗?

谢谢你。

4

1 回答 1

6

您不能在Where子句中使用窗口函数(仅在SELECTor中ORDER BY)。

但是您可以改用CTE

WITH CTE
     AS (SELECT fs.docu_id                    AS docID, 
                fs.field_3                    AS ProductNo, 
                fs.field_4                    AS [Status], 
                fs.field_5                    AS [Index], 
                pd.[doku_nr]                  AS docIDshort, 
                Row_number() OVER( 
                    Partition BY fs.field_3 
                    ORDER BY fs.field_5 DESC) AS rownum 
         FROM   [table1] fs 
                JOIN [table2] pd 
                  ON fs.docu_id = pd.docu_id 
                     AND fs.field_4 = 'valid') 
SELECT docid, productno, status, [index], docIDshort 
FROM   CTE
WHERE  rownum = 1 
于 2013-10-16T13:54:52.557 回答