繁体   English   中英

SQL-按最大日期分组的联接(包括ID)

[英]SQL - Join Grouped By Max Date (Including ID)

假设下表...

ValueHistory ID整数(身份),HistoryDate日期时间,Contract_ID整数,Item_ID整数,Value smallmoney

我想获取最新值(基于HistoryDate)以及与之关联的ID(按Contract_ID和Item_ID分组)。

我目前有这个,它将带出最新的Date / Contract_ID / Item_ID,但是显然我不能按ID分组,因为它会带回太多行。 我考虑使用最大ID,但不幸的是,由于插入日期的方式不同,有可能使用较低的ID,而使用的是最近的日期。

SELECT
    MAX([HistoryDate]) as 'Max_HistoryDate',
    [Contract_ID],
    [Item_ID]
FROM [ValueHistory]
WHERE 
        [HistoryDate] < @EndDate
GROUP BY [Item_ID], [Contract_ID]

我认为可以通过其他子查询来执行此操作,但目前它使我无法幸免。

SQL小提琴在这里: http ://sqlfiddle.com/#!18/655e9/1

按照建议的答案,效果很好。

select
    ID
    , HistoryDate
    , Contract_ID
    , Item_ID
from
(
    SELECT
        HistoryDate
        , ID
        , Contract_ID
        , Item_ID
        , RowNum = ROW_NUMBER() over(partition by Contract_ID, Item_ID order by HistoryDate DESC)
    FROM ValueHistory
    WHERE HistoryDate < @EndDate
) x
where x.RowNum = 1

很确定您想要这样的东西。

select HistoryDate
    , Contract_ID
    , Item_ID
from
(
    SELECT
        HistoryDate
        , Contract_ID
        , Item_ID
        , RowNum = ROW_NUMBER() over(partition by Contract_ID order by HistoryDate DESC)
    FROM ValueHistory
    WHERE HistoryDate < @EndDate
) x
where x.RowNum = 1

我将结果返回到原始表中,并与“项目ID”,“合同ID”和“匹配最大历史日期”的“历史日期”配对。

select *
from
(select *
from [ValueHistory]
) a
join
(
SELECT
    MAX([HistoryDate]) as [Max_HistoryDate],
    [Contract_ID] as [bContract_ID],
    [Item_ID] as [bItem_ID]
FROM [ValueHistory]
WHERE 
    [HistoryDate] < @EndDate
GROUP BY [Item_ID], [Contract_ID]) b

on a.[item_id]=b.[bitem_id] and
    a.[contract_id]=b.[bcontract_id] and
    a.[HistoryDate]=b.[Max_HistoryDate]

使用cte可能会有所帮助:

;with cte (Max_HistoryDate,Contract_ID,Item_ID) as
(
   SELECT
      MAX([HistoryDate]) as 'Max_HistoryDate',
      [Contract_ID],
      [Item_ID]
   FROM [ValueHistory]
   WHERE [HistoryDate] < '2018-02-01'
   GROUP BY [Item_ID], [Contract_ID]
)
Select Value, ih.Contract_ID, ih.Item_ID
From ValueHistory ih
inner join cte on ih.Contract_ID = cte.Contract_ID
               and ih.Item_ID = cte.Item_ID
where ih.HistoryDate = cte.Max_HistoryDate

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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