SQL - 按最大日期分组加入(包括ID)

时间:2018-02-08 14:49:53

标签: sql sql-server

假设下表......

ValueHistory ID int(身份), HistoryDate日期时间, Contract_ID int, Item_ID int, 价值小钱币

我想了解最新的Value(基于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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

我会将结果重新加入原始表格,按照项目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]

答案 2 :(得分:0)

使用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