获取产品的最新版本

Get the latest version of a product

我有一个 table,我在其中输入产品 (SlobID) 的数据

SELECT        TemplateID, SlobID, FromYear, ToYear, MAX(ValidFrom) AS CurrentDate
FROM            CommissionsPerTemplate AS CommissionsPerTemplate_1
GROUP BY TemplateID, SlobID, FromYear, ToYear
HAVING        (MAX(ValidFrom) <= GETDATE()) AND (TemplateID = 2) AND (SlobID = 743)

我得到的结果是

TemplateID  SlobID  (From Year)  (To year)   Valid date
2            743        1          1        2016-01-01
2            743        1            99     2015-01-01
2            743        2            99     2016-01-01

困难的部分是我们需要查询才能获得该产品的最新版本。 第一个版本 (1/1/2015) 如果从 year=1 到 year=99 但第二个版本创建于(1/1/2016),它分裂了岁月 从第 1 年到第 1 年以及从第 2 年到第 99 年。

所以对我来说正确的结果应该是下面的

TemplateID  SlobID  (From Year)  (To year)   Valid date
2            743        1            1      2016-01-01
2            743        2            99     2016-01-01

但我不知道如何获得它。 也许在 2017 年 1 月 1 日,新版本应该从 year =1 到 year=10 以及从 year =11 到 year =99 或其他。

不确定这是否适用于其余数据,但如果您使用 row_number 而不是分组依据并从分区依据中取出 "to year" 它适用于您的样本数据。

select * from 
(
SELECT        TemplateID, SlobID, FromYear, ToYear, ValidFrom As CurrentDate , row_number () over ( partition by TemplateID, SlobID,FromYear  order by ValidFrom desc) rowid
FROM            CommissionsPerTemplate AS CommissionsPerTemplate_1
where  (TemplateID = 2) AND (SlobID = 743)
) as x 
where rowid = 1