我有一个包含以下列的表格:
Document_ID, Customer_ID, Date, LoanedMoney.
我创建了一个新LoanedDate
列。我想LoanedDate
通过以下方式填写日期:
- 如果前一个
Date
或前一个日期不存在(它并不意味着总是-1天)Document_ID
并且Customer_ID
为空 -> 复制LoanedMoney
值并使用该值更新; - 如果前一个
Date
(并不意味着总是-1天)具有相同Document_ID
且不Customer_ID
为空->复制它并使用该值进行更新; - 其他设置
NULL
为LoanedDate
我确定上一个日期的大致逻辑(不知道如何将其放在case语句中):
SELECT TOP 1 Z1.Date
FROM DBANME Z1
LEFT JOIN DBNAME Z2
ON Z1.Document_ID = Z2.Document_ID AND Z1.Customer_ID = Z2.Customer_ID AND CONVERT(CHAR(8), Z1.Date, 112) < CONVERT(CHAR(8), Z2.Date, 112)
ORDER BY Date DESC
我做了这样的事情:
DECLARE @Min datetime, @Prev datetime
SELECT @Min = MIN(Date) FROM DBNAME
UPDATE DBNAME
SET LoanedDate CASE
WHEN (LoanedMoney > 0)
-- SET @Prev =
CASE WHEN @Prev IS NULL THEN Date
ELSE @Prev
ELSE NULL
实施它的最佳方法是什么?
我有的:
Document_ID, Customer_ID, Date, LoanedMoney, LoanedDate
1, 1, 2012-04-30, 30, NULL
1, 1, 2012-04-29, 50, NULL
1, 1, 2012-04-28, 50, NULL
1, 1, 2012-04-27, 0, NULL
1, 1, 2012-04-26, 20, NULL
我的期望:
Document_ID, Customer_ID, Date, LoanedMoney, LoanedDate
1, 1, 2012-04-30, 30, 2012-04-28
1, 1, 2012-04-29, 50, 2012-04-28
1, 1, 2012-04-28, 50, 2012-04-28
1, 1, 2012-04-27, 0, NULL -- Because LoanedMoney = 0
1, 1, 2012-04-26, 20, 2012-04-26