SQL Server查询 - 仅选择每个产品代码的第一行

时间:2014-07-24 18:31:47

标签: sql-server sql-server-2008-r2

我需要对我的产品列表的最后一个购买价格进行过滤,但我只需要每个产品的第一行(它已经在正确的订单上)。

示例:

PRODUCT CODE                    PRICE      PURCH.DATE
-----------------------------------------------------
PO.MC.PER.001.N.PORTVIDEOCARD   0,3      20140521
PO.MC.PER.001.N.PORTVIDEOCARD   0,3      20140203
PO.MC.PER.001.N.PORTVIDEOCARD   0,3     20131115
PO.MC.PER.001.N.PORTVIDEOCARD   0,6     20130625
PO.MC.PER.001.N.PORTVIDEOCARD   0,5     20121122
SV.AI.SEI.006.N.CONFIEQUIPARE   800     20121211
SV.AI.SEI.006.N.CONFIEQUIPARE   3675    20121211
SV.AI.SEI.006.N.CONFIEQUIPARE   2000    20121114
SV.AI.SEI.006.N.CONFIEQUIPARE   2000    20120904
SV.AI.SFT.001.N.SOFTGERENCAME   2184    20121210
TI.AI.COP.001.N.NOTEBOOKPCXXX   3020,28 20110902
TI.AI.COP.002.N.COMPUTDESKTOP   2466,47 20140123
TI.AI.COP.002.N.COMPUTDESKTOP   2572    20131107
TI.AI.COP.002.N.COMPUTDESKTOP   2320    20131001
TI.AI.COP.002.N.COMPUTHP300GB   1517,5  20111130
TI.AI.COP.002.N.HPSMARTARRAYP   548,7   20111130
TI.AI.COP.002.N.UTRIUM920SAS    6050,6  20111130
TI.AI.COP.006.N.NOTEBOOKHPXXX   3020,28 20111117
TI.AI.COP.008.N.COMPUTINTELXE   1715    20111130
TI.AI.COP.009.N.COMPHP460WCSH   916,6   20111130
TI.AI.COP.011.N.MONITCOMPUTAD   25      20130613
TI.AI.COP.011.N.MONITCOMPUTAD   478     20130521

然后我希望得到以下结果:

PRODUCT CODE                    PRICE      PURCH.DATE
-----------------------------------------------------       
PO.MC.PER.001.N.PORTVIDEOCARD   0,3      20140521
SV.AI.SEI.006.N.CONFIEQUIPARE   800     20121211
SV.AI.SFT.001.N.SOFTGERENCAME   2184    20121210
TI.AI.COP.001.N.NOTEBOOKPCXXX   3020,28 20110902
TI.AI.COP.002.N.COMPUTDESKTOP   2466,47 20140123
TI.AI.COP.002.N.COMPUTHP300GB   1517,5  20111130
TI.AI.COP.002.N.HPSMARTARRAYP   548,7   20111130
TI.AI.COP.002.N.UTRIUM920SAS    6050,6  20111130
TI.AI.COP.006.N.NOTEBOOKHPXXX   3020,28 20111117
TI.AI.COP.008.N.COMPUTINTELXE   1715    20111130
TI.AI.COP.009.N.COMPHP460WCSH   916,6   20111130
TI.AI.COP.011.N.MONITCOMPUTAD   25      20130613

因此,最终查询只会显示每个产品的最后价格,ONCE

我无法使用distinct,因为它们已经明显不同了(虽然产品重复,但价格和/或购买日期并非如此)

我正在使用SQL Server 2008 R2

2 个答案:

答案 0 :(得分:1)

您可以使用row_number函数:

with CTE as
(select
[Product Code],
[Price],
[Purch.date],
row_number() over (partition by [product code] order by [purch.date] desc) as RN
from
<your table>
)

select * from CTE
where
RN = 1

答案 1 :(得分:1)

看看它是否有效:

 WITH cte AS
    (
       SELECT *,
             ROW_NUMBER() OVER (PARTITION BY PRODUCTCODE ORDER BY PURCHDATE DESC) AS rn
       FROM Table
    )
    SELECT *
    FROM cte
    WHERE rn = 1