最后一个值基于标准

时间:2017-10-17 18:16:44

标签: sql sql-server

我使用以下查询从SQL Server中提取数据。

SELECT  
"vendor"."vendornum" AS Number, 
"vendor"."vendornam" AS Name,
"product"."prductnum" AS ProductNumber 
"product"."prductdsc" AS Description 
"po_lnrcpt"."um_code",
"porcpt"."received_date" AS DateReceived,
"po_lnrcpt"."ovruntcst" AS Price, 

FROM   
(((("Test"."dbo"."company" "company" INNER JOIN 
"Test"."dbo"."porcpt" 
"porcpt" ON "company"."co_num"="porcpt"."co_num")
INNER JOIN 
"Test"."dbo"."po" "po" ON "porcpt"."po_tky"="po"."po_tky") 
LEFT OUTER JOIN 
"Test"."dbo"."po_lnrcpt" "po_lnrcpt" ON 
"porcpt"."po_rcvtky"="po_lnrcpt"."po_rcvtky") 
LEFT OUTER JOIN 
"Test"."dbo"."product" "product" ON 
"po_lnrcpt"."prdtky"="product"."prdtky") 
LEFT OUTER JOIN 
"Test"."dbo"."vendor" "vendor" ON 
"po"."ventky"="vendor"."ventky"

 WHERE  
 "po_lnrcpt"."rcvqty"<>0 AND 
 "porcpt"."rcvstsflg"='C' 

无论如何,我可以使用MAX或其他功能来显示特定供应商的产品的最新价格。

先谢谢

1 个答案:

答案 0 :(得分:1)

这是CTE的快速方法。这也可以与原始查询中的另一个内部联接一起用餐。此外,您可以使用ROW_NUMBER()。这不是假设DateReceived列是确定“最新”

的日期列
with cte as(
SELECT  
    vendor.vendornum AS Number, 
    vendor.vendornam AS Name,
    product.prductnum AS ProductNumber 
    product.prductdsc AS Description 
    po_lnrcpt.um_code,
    porcpt.received_date AS DateReceived,
    po_lnrcpt.ovruntcst AS Price, 

FROM   
Test.dbo.company company INNER JOIN 
Test.dbo.porcpt 
porcpt ON company.co_num=porcpt.co_num
INNER JOIN 
Test.dbo.po po ON porcpt.po_tky=po.po_tky
LEFT OUTER JOIN 
Test.dbo.po_lnrcpt po_lnrcpt ON 
porcpt.po_rcvtky=po_lnrcpt.po_rcvtky
LEFT OUTER JOIN 
Test.dbo.product product ON 
po_lnrcpt.prdtky=product.prdtky
LEFT OUTER JOIN 
Test.dbo.vendor vendor ON 
po.ventky=vendor.ventky

WHERE  
 po_lnrcpt.rcvqty<>0 AND 
 porcpt.rcvstsflg='C')



select
    c.Number
    ,c.Name
    ,c.ProductNumber
    ,c.Description
    ,c.um_code
    ,c.DateReceived
    ,c.Price
from cte c
inner join
    (select Number, max(DateReceived) dt
     from cte
     group by Number) c2 on c2.dt = c.DateReceived and c2.Number = c.Number

ROW_NUMBER()版本

with cte as(
SELECT  
    vendor.vendornum AS Number, 
    vendor.vendornam AS Name,
    product.prductnum AS ProductNumber 
    product.prductdsc AS Description 
    po_lnrcpt.um_code,
    porcpt.received_date AS DateReceived,
    po_lnrcpt.ovruntcst AS Price, 
    RN = row_number() over (partition by vendor.vendornum order by porcpt.received_date desc)
FROM   
Test.dbo.company company INNER JOIN 
Test.dbo.porcpt 
porcpt ON company.co_num=porcpt.co_num
INNER JOIN 
Test.dbo.po po ON porcpt.po_tky=po.po_tky
LEFT OUTER JOIN 
Test.dbo.po_lnrcpt po_lnrcpt ON 
porcpt.po_rcvtky=po_lnrcpt.po_rcvtky
LEFT OUTER JOIN 
Test.dbo.product product ON 
po_lnrcpt.prdtky=product.prdtky
LEFT OUTER JOIN 
Test.dbo.vendor vendor ON 
po.ventky=vendor.ventky

WHERE  
 po_lnrcpt.rcvqty<>0 AND 
 porcpt.rcvstsflg='C')



select
    c.Number
    ,c.Name
    ,c.ProductNumber
    ,c.Description
    ,c.um_code
    ,c.DateReceived
    ,c.Price
from cte c
where RN = 1