如何从视图中检索最大值?

时间:2015-01-25 01:44:07

标签: sql sql-server

我有这个观点,我想选择maximum SALE PRICE

[Barcode No]    [LType]     [Description    ]   [UOM]  [Sale Price]
045300005492    CF00683     PETER PAN PBUTTER   PCS    23.5
045300005492    CF00683     PETER PAN PBUTTER   PCS    13.5
045300005492    CF00683     PETER PAN PBUTTER   PCS    13.5

我尝试使用以下SQL声明,但这对我不起作用:

select [Barcode No],[ITEM NO],[Description],[SUM],max([Sales Price]) 
from [Table1]

1 个答案:

答案 0 :(得分:1)

您需要在group by

中添加非聚合列
select [Barcode No],[ITEM NO],[Description],[SUM],max([Sales Price]) 
from [Table1]
Group by [Barcode No],[ITEM NO],[Description],[SUM]

或使用Window Function

SELECT [Barcode No],[ITEM NO],[Description],[SUM],[Sales Price]
FROM   (SELECT [Barcode No],[ITEM NO],[Description],[SUM],[Sales Price],
               Row_number()OVER(partition BY [Barcode No], [ITEM NO], [Description], [SUM]
                   ORDER BY [Sales Price] DESC) rn
        FROM   [Table1])a
WHERE  rn = 1