简体   繁体   中英

Getting latest date in SQL query

I am running this query right now:

WITH Result AS (

select distinct
    --pump.Product_PN,
    --pump.product_name,
    mot.Motor_pn,
    Mot.Motor_name,
    mas.STLAN AS Usage,
    po.DATUV as change_date,
    mot.[Procurement type],
    mot.Plant as plant, 
    po.IDNRK AS Component_PN,
    mak.MAKTG as component_name


FROM dbo.TBLMAST AS mas
INNER JOIN dbo.TBLSTPO AS po
    ON mas.STLNR = po.STLNR
INNER JOIN dbo.TBLMAKT AS mak 
    ON mak.MATNR = po.IDNRK


--INNER JOIN ['Pumps to motor$'] AS pump
    --ON pump.[Motor Product Number] = SUBSTRING(mas.MATNR, PATINDEX('%[^0 ]%', mas.MATNR + ' '), LEN(mas.MATNR))

INNER JOIN Grundfos_motors AS mot
    ON mot.Motor_PN = SUBSTRING(mas.MATNR, PATINDEX('%[^0 ]%', mas.MATNR + ' '), LEN(mas.MATNR))


where mas.STLAN = '8' and mot.Motor_PN = '78085617' and mak.MAKTG like '%stator%'

 )

 select motor_pn, motor_name, plant, change_date, Component_PN, Component_name, cast(getdate() as date) as Date_of_Extraction_date

 from result



 order by change_date DESC;

The result of this query is this:

查询1

From this query result, I want to run another query where the change_date is set to the latest. So I only want to retrieve the data for the latest date and rest is excluded. Something like:

结果

Can anyone help?

You should be able to do:

select motor_pn, motor_name, plant, change_date, Component_PN, Component_name,
       cast(getdate() as date) as Date_of_Extraction_date
from (select r.*,
             row_number() over (partition by motor_pn order by change_date desc) as seqnum
      from result r
     ) r
where seqnum = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM