SQL:如何选择最新的版本化项目

时间:2016-01-19 14:29:06

标签: sql sql-server sql-server-2012

在我们的系统中,项目会根据可用时间而有不同的版本。 例如。 “工具1”项目的版本可用于以下日期:

  • Version 1:01.01.2015 - 2015年12月31日
  • Version 2:01.01.2016 - 31.01.2016
  • 第3版:01.02.2016 - 29.02.2016
  • 第4版:01.03.2016 - 直至另行通知

因此,我在DB中的“工具”表是

ItemCode   |    ParentCode   |    EffectiveFrom    
1          |    1            |    01.01.2015
2          |    1            |    01.01.2016
3          |    1            |    01.02.2016
4          |    1            |    01.01.2016

现在,Mgmt想知道哪些物品正在销售,哪些物品即将推出。 ParentCode指的是项目的第一个版本。

因此,他们需要ItemCodes 2(目前正在销售)和3,4(即将推出)。无法找到一种方法让SELECT获得这些。

使用“Microsoft SQL Server Management Studio 2012”。

感谢您的帮助。

此致

2 个答案:

答案 0 :(得分:2)

我认为这只是对当前日期的比较以及有关下一个日期的信息。

最好将结束日期直接放在表中,但在SQL Server 2012+中,可以使用lead()轻松计算:

select t.*,
       (case when effectivefrom >= getdate() then 'Coming Soon'
             else 'Currently Sold'
        end) as timingStatus
from (select t.*,
             lead(effectivefrom) over (partition by parentcode order by effectivefrom) as next_effectivefrom
      from tools t
     ) t
where next_effectivefrom is null or next_effectivefrom >= getdate();

注意:这使用具有时间组件的getdate()。你的约会时间可能不合适。所以,我认为以下内容稍微准确一些:

select t.*,
       (case when effectivefrom > cast(getdate() as date) then 'Coming Soon'
             else 'Currently Sold'
        end) as timingStatus
from (select t.*,
             lead(effectivefrom) over (partition by parentcode order by effectivefrom) as next_effectivefrom
      from tools t
     ) t
where next_effectivefrom is null or
      next_effectivefrom > cast(getdate() as date);

答案 1 :(得分:0)

这个答案可能不是你想要的答案,但你可以试试这个:

SELECT * 
FROM Tools 
WHERE EffectiveForm > CONVERT(NVARCHAR(10),GETDATE(),104)
OR (MONTH(EffectiveForm) = MONTH(GETDATE()) 
    YEAR(EffectiveForm) = YEAR(GETDATE()))
相关问题