如何在SQL中的特定记录之间插入记录

时间:2013-05-15 12:36:50

标签: sql-server sql-server-2008 cursor

假设我有一个客户余额明细表。例如:

CustID    CustName  CustDate    Amt   Bal
1          DP       1/5/2013   1000  1000
1          DP       5/5/2013   100   1100
1          Dhara    10/5/2013  1000  1000
1          DP       10/5/2013  1000  2100

现在用户插入记录CustName = DP,CustDate = 7/5/2013,Amt = 400然后该记录应该在2013年5月5日之后和2013年10月5日之前添加,并且相应的余额也应该更改如下:

CustID    CustName  CustDate    Amt   Bal
1          DP       1/5/2013   1000  1000
1          DP       5/5/2013   100   1100
1          DP       7/5/2013   400   1500
1          Dhara    10/5/2013  1000  1000
1          DP       10/5/2013  1000  2500

在数据库中插入记录时如何实现?如何检查日期是否已插入记录之间?请帮忙

2 个答案:

答案 0 :(得分:0)

我认为,如果您使用ORDER BY子句以所需顺序访问数据,则可以获得所需内容。另请参阅您的数据库文档以了解索引的使用。

答案 1 :(得分:0)

以下是关于如何做的一个建议:http://www.sqlfiddle.com/#!3/d341b/9

CREATE TABLE Customer
(
  CustId INT,
  CustName NVARCHAR(150),
  CustDate DATE,
  Amt INT,
)

INSERT INTO Customer
    (CustID, CustName, CustDate, Amt)
VALUES
    (1, 'DP', '2013-01-05 00:00:00', 1000),
    (1, 'DP', '2013-05-05 00:00:00', 100),
    (1, 'DP', '2013-07-05 00:00:00', 400),
    (1, 'Dhara', '2013-10-05 00:00:00', 1000),
    (1, 'DP', '2013-10-05 00:00:00', 1000)
;

;WITH RankedCustomer AS
(
  SELECT
    CustId
    , CustName
    , CustDate
    , Amt
    , ROW_NUMBER() OVER(ORDER BY CustDate) Row
  FROM
    Customer
)
SELECT
  Customer.CustId
  , Customer.CustName
  , Customer.CustDate
  , Customer.Amt
  , SUM(PreviousCustomer.Amt)
FROM
  RankedCustomer Customer
  LEFT JOIN RankedCustomer PreviousCustomer
    ON PreviousCustomer.CustId = Customer.CustId
    AND PreviousCustomer.CustName = Customer.CustName
    AND PreviousCustomer.Row <= Customer.Row
GROUP BY
  Customer.CustId
  , Customer.CustName
  , Customer.CustDate
  , Customer.Amt
ORDER BY
  Customer.CustDate