-1

我有这两张表:

表 1:客户姓名账单日期

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

等等...

表 2 具有字段:CycleStartDate

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

我们有可能做这样的事情吗?

4

2 回答 2

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
于 2013-08-12T19:34:49.213 回答
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() 函数

于 2013-08-12T19:39:40.110 回答