Updating Parent table records with sum of chile records

  • Hi All.

    SQL Server 2000

    Can someone please help with the following: -

    Structure:

    tblCustomer

    CustomerID (int)

    PaymentCount (int)

     

    tblPayment

    CustomerID (int)

    PaymentID (int)

    PaymentDate (datetime)

    I want to update the customer (PaymentCount) with the total number of related payments in tblPayment.

    Can someone help me with the Update tsql.

    Thankyou

    CCB.

  • DECLARE @tblCustomer TABLE( CustomerID integer, 

                                                 PaymentCount integer)

    INSERT INTO @tblCustomer

    SELECT 1, NULL UNION ALL

    SELECT 2, NULL UNION ALL

    SELECT 3, NULL UNION ALL

    SELECT 4, NULL UNION ALL

    SELECT 5, NULL

    DECLARE @tblPayment TABLE( CustomerID integer, 

                                                PaymentID integer, 

                                                PaymentDate datetime)

    INSERT INTO @tblPayment

    SELECT 1, 1, '12/31/2002' UNION ALL

    SELECT 1, 2, '1/28/2003' UNION ALL

    SELECT 2, 1, '12/31/2002' UNION ALL

    SELECT 2, 2, '1/31/2003' UNION ALL

    SELECT 2, 3, '2/28/2003' UNION ALL

    SELECT 3, 1, '12/31/2002' UNION ALL

    SELECT 4, 1, '12/31/2002' UNION ALL

    SELECT 4, 2, '6/1/2003' UNION ALL

    SELECT 5, 1, '12/31/2002' UNION ALL

    SELECT 5, 2, '6/1/2003' UNION ALL

    SELECT 5, 3, '12/31/2003' UNION ALL

    SELECT 5, 4, '6/1/2004'

    UPDATE @tblCustomer SET

             PaymentCount = PC.PaymentCount

    FROM @tblCustomer Customer

       INNER JOIN( SELECT CustomerID, COUNT(*) AS PaymentCount

                           FROM @tblPayment

                           GROUP BY CustomerID) PC ON(  Customer.CustomerID = PC.CustomerID)

    SELECT * FROM @tblCustomer

    I wasn't born stupid - I had to study.

  • UPDATE tblCustomer

     SET PaymentCount = (SELECT Count(PaymentID) FROM tblPayment P WHERE P.CustomerID = C.CustomerID)

     FROM tblCustomer C

  • Farrell, that worked a treat.

    Thanks

    CCB.

  • Glad to help. 

    I wasn't born stupid - I had to study.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply