Frage

I must be doing something wrong. I'm trying to use the row_number function to only select the values that have a rownum of 1, so that I always get the latest index. However rownum is not recognized in the where-clause.

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'

What am I missing? Do I need to create a different select stmt?

Thank you.

War es hilfreich?

Lösung

You cannot use window functions in the Where clause(only in SELECT or ORDER BY).

But you could use a CTE instead:

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 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top