在ROW_NUMBER之后添加MAX功能

时间:2018-06-01 18:06:33

标签: sql sql-server tsql

我有以下代码:

SELECT 
    * 
FROM 
    (SELECT 
         ROW_NUMBER () OVER (PARTITION BY PO_Number, PO_Value, Supplier 
                             ORDER BY Date_PurchaseOrder) AS Line_Count, 
         * 
     FROM 
         Table_PO) AS T 
WHERE
    Line_Count = 1 

相应地返回Line_Count。但是,我想使用WHERE函数来返回最高计数,而不是MAX子句。我尝试了一些样品,但没有工作。

我需要使用最高Date_PurchaseOrder并忽略其他日期。

由于PO_Number可以有多个Date_PurchaseOrder,我只需要列中的最后一个日期。

提前致谢。

1 个答案:

答案 0 :(得分:1)

改为使用subquery

select tp.*
from Table_PO tp
where Date_PurchaseOrder = (select max(Date_PurchaseOrder)
                            from Table_PO tp1
                            where tp1.PO_Number = tp.PO_Number
                           );

但是,您也可以使用dense_rank()功能:

select *
from (select *, dense_rank() over (partition by PO_Number 
                                        order by Date_PurchaseOrder desc) as Seq
      from Table_PO 
     ) tp
where Seq = 1;

编辑:只需按DESC

订购
SELECT * 
FROM (SELECT *, 
             ROW_NUMBER() OVER (PARTITION BY PO_Number, PO_Value, Supplier 
                                     ORDER  BY Date_PurchaseOrder DESC) AS Line_Count
      FROM Table_PO 
      ) AS T 
Where Line_Count = 1;