SQL Server将以前的值插入新列

时间:2013-08-12 19:22:44

标签: sql sql-server

我有这两个表:

表1: 客户名称BillDate

CITY - BEAUTIFICATION LM            2013-05-30 00:00:00.000
CITY - BEAUTIFICATION LM            2013-06-28 00:00:00.000
CITY - PARKS/RT 66                  2012-07-12 00:00:00.000
CITY - PARKS/RT 66                  2012-07-12 00:00:00.000

依旧......

Table2的字段为:CycleStartDate

我想将Table1中的数据插入到Table2中,如下所示: 对于每个唯一的customerName,CycleStartDate是前一记录中的BillDate。如果先前的记录不存在,请将NULL替换为2013-07-1 00:00:00.000。

我们可以做那样的事吗?

2 个答案:

答案 0 :(得分:0)

嗯,这是假设SQL Server 2005 +的一种方式:

;WITH CTE AS
(
    SELECT  CustomerName,
            BillDate,
            RN1=ROW_NUMBER() OVER(PARTITION BY CustomerName ORDER BY BillDate),
            RN2=ROW_NUMBER() OVER(PARTITION BY CustomerName ORDER BY BillDate DESC)
    FROM dbo.Table1
)
INSERT INTO dbo.Table2(CustomerName, CycleStartDate)
SELECT  CustomerName,
        CASE WHEN RN2 = 1 THEN '20130701' ELSE CycleStartDate END
FROM CTE
WHERE RN1 = 1

答案 1 :(得分:0)

如果SQL Server少于2012,请尝试使用

select T.CustomerName, isnull(TP.BillDate, '20130701') as CycleStartDate
from Table1 as T
   outer apply (
       select top 1 T2.BillDate
       from Table1 as T2
       where T2.CustomerName = T.CustomerName and T2.BillDate < T.BillDate
       order by T2.BillDate desc
   ) as TP

如果您有SQL Server 2012,请参阅LAG()功能