我一定是做错了。我正在尝试使用row_number函数来仅选择具有 1 的rownum的值,以便我始终获得最新的索引。但是,在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'
我错过了什么?我是否需要创建不同的select stmt?
谢谢。
答案 0 :(得分:5)
您无法在Where
子句中使用窗口函数(仅限SELECT
或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