新行基于sql server 2008中的计算列

时间:2016-05-12 11:01:58

标签: sql sql-server

我有一个如下表格 - sql server 2008

我正在尝试为特定的FINDID 列创建一个名为NEW_DATE的

第一条记录的新日期将比第二条记录的FROM_DATE减少-1秒,依此类推......

行按from_date升序排序 新日期其中识别= 1始终保持' 12/31/9999 12:00:00 AM

DDL:

CREATE TABLE MYTABLE
(
FINDID  INT,
SUPPLIERID INT  ,
SUPPLIERSKU VARCHAR (35),
PRICE   decimal (14,4),
FROM_DATE datetime  ,
IDENTIFY bit
)

INSERT MYTABLE

SELECT 1000001, 1001,   '012RE0020',    4,  '5/12/2016  6:49:40 AM',    0 UNION ALL
SELECT 1000001, 1001,   '012RE0020',    4,  '5/12/2016  7:16:24 AM',    0 UNION ALL
SELECT 1000001, 1001,   '012RE0020',    5,  '5/12/2016  7:52:55 AM',    1 UNION ALL
SELECT 1000002, 1001,   '101ME0320',    21, '5/12/2016  6:49:40 AM',    0 UNION ALL
SELECT 1000002, 1001,   '101ME0320',    21, '5/12/2016  7:16:24 AM',    0 UNION ALL
SELECT 1000002, 1001,   '101ME0320',    26, '5/12/2016  7:33:38 AM',    0 UNION ALL
SELECT 1000002, 1001,   '101ME0320',    27, '5/12/2016  7:52:55 AM',    1

输出看起来像

FINDID  SUPPLIERID  SUPPLIERSKU PRICE   FROM_DATE   NEW_TO_DATE IDENTIFY
1000001 1001    012RE0020   4   5/12/2016  6:49:40 AM   5/12/2016  7:16:23 AM   0
1000001 1001    012RE0020   4   5/12/2016  7:16:24 AM   5/12/2016  7:52:54 AM   0
1000001 1001    012RE0020   5   5/12/2016  7:52:55 AM   12/31/9999  12:00:00 AM 1
1000002 1001    101ME0320   21  5/12/2016  6:49:40 AM   5/12/2016  7:16:23 AM   0
1000002 1001    101ME0320   21  5/12/2016  7:16:24 AM   5/12/2016  7:33:37 AM   0
1000002 1001    101ME0320   26  5/12/2016  7:33:38 AM   5/12/2016  7:52:54 AM   0
1000002 1001    101ME0320   27  5/12/2016  7:52:55 AM   12/31/9999  12:00:00 AM 1

如果可能的话,有人可以帮助我吗

2 个答案:

答案 0 :(得分:1)

在SQL Server 2012+中,您只需使用lead()即可。在SQL Server 2008中,您可以使用相关子查询或outer apply

执行此操作
select t.*,
       coalesce(t2.from_date, '9999-12-31') as new_to_date
from mytable t outer apply
     (select top 1 t2.*
      from mytable t2
      where t2.findid = t.findid and t2.from_date > t.from_date
     ) t2;

答案 1 :(得分:1)

我建议你创建一个这样的视图:

1)MSBuild.SonarQube.Runner.exe /k ... /n ... /v...
2)C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe /t:Rebuild
3)MSBuild.SonarQube.Runner.exe end

输出:

CREATE VIEW dbo.MyView
AS
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY FINDID ORDER BY FINDID, FROM_DATE) as RN
FROM MYTABLE m
)

SELECT  c.FINDID,
        c.SUPPLIERID, 
        c.SUPPLIERSKU,
        c.PRICE,
        c.FROM_DATE,
        ISNULL(DATEADD(second,-1,c2.FROM_DATE),'12/31/9999  12:00:00 AM') as NEW_TO_DATE,
        c.IDENTIFY
FROM cte c
LEFT JOIN cte c2
    ON c2.RN = c.RN + 1 AND c.FINDID = c2.FINDID;
GO