Loop and Insert Question

Last post 08-09-2008, 12:49 PM by Phil Factor. 1 replies.
Sort Posts: Previous Next
  •  08-05-2008, 11:19 AM Post number 66388

    Loop and Insert Question

    Hi,

    I am totaly new to SQL. I have a database, where I have an ID Number as well as a Price Number which I would like to add up for the Items I bought in each week so that I know how much I spend in each week. It looks something like this:

    ID      Price      Purchased Week   Summary
    1         199         1                          -
    2         79            1                         -
    ...         ...            ..
    20      150         5                           -

    I tried something like this, but it won't work, maybe someone can help me, cause it's getting much more complicated.. I know the following is very wrong...

    DECLARE @summary INT
    DECLARE @id INT
    SET @summary = 0
    SET @id = 0
    WHILE (@id < 5000)
        BEGIN
            SELECT DISTINCT Price FROM PurchasesTest
            WHERE Week = 1
            SET @summary = @summary + Price  
            INSERT INTO PurchasesTest (Summary) VALUES = @summary
        END

    Please help...

    Tnx


  •  08-09-2008, 12:49 PM Post number 67014 in reply to post number 66388

    Re: Loop and Insert Question

    At a simple level, you just need the total per week. I'm not clear if the purchased column is the quantity purchased. If so, then this would do the trick.

    Select week, sum(price*purchased) from PurchasesTest group by week


    From your SQL, it looks as if you are attempting to do a running total, which is fine and we can certainly do that. That would tell you not only what you've spent but also how much money you have left. Is that what you intend?
View as RSS news feed in XML