如何获取给定表的先前Id值?

时间:2017-03-14 06:54:31

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

我有两个输入表:

1)网站:

 site_id||   site_name||   site_location

 1000   ||    abc     ||    XYZ_123
 1001   ||    tyu     ||    ERD_123
 1002   ||    iok     ||    FTR_678
 1003   ||    okn     ||    YHU_987
 1004   ||    ybg     ||    OLP_008
 1005   ||    qwe     ||    PLM_126

2)

产物:

 Product_id|| product_name||start_date||end_date

   212     || sme1        ||2014-12-25||2017-03-13
   250     || try1        ||2013-12-15|| 2017-03-13
   267     || inu1        || 2015-03-27|| 2017-03-17

我需要检查id重复的次数,并将其命名为输出表。

如果preoduct_id重复并且小于结束日期,那么previousId将被计算。

这就是我现在所做的事情。

select top 1 d2.PRODUCT_id, d2.last_date, d1.*
from output_table d1,
     output_table  d2 
where d1.SITE_id = d2.Site_id
  and d1.START_DATE >= d2.end_DATE
  and d1.Site_id=1001
  and d1.PRODUCT_id = 250
order by d2.End_date desc 

感谢任何帮助。

我需要输出我的表格。

这是我的输出表结构:

Id|| site_id|| product_id|| previous_id|| start_date|| end_date  ||Previous_site_id || repeated_times || Previous_id

1 || 1000   ||250        || null       || 2015-01-01||2017-03-13 || 1001            ||3              || 2
2 || 1001   ||250        || 1          || 2014-12-25||2015-01-01 || 1002            ||3               || 3
3 || 1002   ||250        || 2          || 2013-12-15||2014-12-25 || Null            ||3               || Null
4 || 1003   ||267        || null       || 2015-03-27|| 2017-03-17|| Null            ||0               || Null
5 ||1004    ||212        || null       || 2016-01-01||2017-03-13 ||1004             ||2               || 6
6 || 1005   ||212        || 1          || 2014-12-25||2015-12-30 ||Null             ||2               || Null

1 个答案:

答案 0 :(得分:0)

由于您提供的架构描述非常糟糕,我猜测已经做了很多。考虑到您使用MSSQL 2012,应该有LAG窗口函数,可以某种方式使用,类似于以下内容:

WITH CountedResult AS
(
    SELECT
        ROW_NUMBER() OVER(ORDER BY product_id, site_id) AS Id, -- use some id instead, if you have
        site_id,
        product_id,
        [start_date],
        [end_date],
        COUNT(*) OVER(PARTITION BY product_id) AS repeated_times
    FROM output_table
    WHERE
        site_id=1001
        AND product_id = 250
)
SELECT 
    Id, site_id, product_id, [start_date], [end_date],
    LAG(site_id, 1, 0) OVER (PARTITION BY product_id ORDER BY [start_date] DESC) AS previous_site_id,
    repeated_times,
    LAG(Id, 1, 0) OVER (PARTITION BY product_id ORDER BY [start_date] DESC) AS previous_id,
FROM CountedResult
ORDER BY product_id, site_id

详细了解MSDN上的LAGhttps://msdn.microsoft.com/en-us/library/hh231256.aspx