T-Sql如何获取Max日期记录?

时间:2017-10-01 09:55:46

标签: sql-server tsql

我想要每GroupCode个最大日期行 我写了这个。

SELECT FH.BelgeNo AS FaturaNo
    ,FHD.UrunId
    ,FH.Tarih
    ,UG.Grup AS GrupKodu
    ,FHD.Kodu
    ,FHD.UrunAdi
    ,FHD.BirimFiyat
FROM FirmaHareketDetayi FHD
LEFT JOIN FirmaHareketleri FH ON FH.ID = FHD.HareketId
LEFT JOIN Urunler U ON U.UrunId = FHD.UrunId --and U.Kodu = FHD.Kodu
LEFT JOIN UrunGruplari UG ON UG.GrupId = U.GrupId
WHERE FHD.Kodu = '2S619H307CF'
    AND FH.FirmaId = 2610
ORDER BY Tarih DESC 

,结果就像这样

有2 PIERBURG行。 enter image description here

是否可以只获得一个PIERBURG? 我的意思是最大日期(Tarih:Date列,GrupKodu:Group Code)

注意:表UrunGrupları:ProductGroups 表FirmaHareketleri:FirmMovements 表FirmaHareketDetayi:FirmMovementDetails(由HareketId(外键)与FirmMovements连接)

对不起我的英文:(

1 个答案:

答案 0 :(得分:0)

您可以使用此功能的窗口功能

    ;with cte as (
    SELECT FH.BelgeNo AS FaturaNo
        ,FHD.UrunId
        ,FH.Tarih
        ,UG.Grup AS GrupKodu
        ,FHD.Kodu
        ,FHD.UrunAdi
        ,FHD.BirimFiyat
        , row_number() over(partition by UG.Grup order by FH.Tarih desc) as rownum
    FROM FirmaHareketDetayi FHD
    LEFT JOIN FirmaHareketleri FH ON FH.ID = FHD.HareketId
    LEFT JOIN Urunler U ON U.UrunId = FHD.UrunId --and U.Kodu = FHD.Kodu
    LEFT JOIN UrunGruplari UG ON UG.GrupId = U.GrupId
    WHERE FHD.Kodu = '2S619H307CF'
        AND FH.FirmaId = 2610    
    )

    select *
    from cte
    where rownum = 1