SUM function assistance

  • I'm going to feel real dumb when someone posts the answer to this because I know it's real simple. I just can't focus right now.

    I have a table called accounts

    It has over 800 records.

    I need to select the distinct DESCRIPTIONS (easy... and there are 156 distinct records)

    Now for the 156 records, I need to SUM the total (column is called balance) of the balance for each distinct record.

    So let's say I have a record in the Descriptions column called Peanuts and there are 10 distinct occurrences of peanuts. I need the sum of those 10 occurrences. I can do this no problem, but I want a script that doesn't require me to hard code the description value. :crazy:

  • Is this it?

    SELECT Description, SUM(Balance)

    FROm Table

    GROUP BY Description

  • I knew it so was simple. I was using distinct and that was throwing the whole thing off... I feel real dumb right now... Sorry for wasting your time. 🙁

  • SQL_Enthusiast-AZ (3/4/2012)


    I knew it so was simple. I was using distinct and that was throwing the whole thing off... I feel real dumb right now... Sorry for wasting your time. 🙁

    I wouldn't call it a waste of time at all. You learned something and you wrote a decent post to help us figure what you were talking about. Heh... you should see some of the simple stuff I get stuck on when I haven't had enough coffee. 😛

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • Hi

    Pls try below code.

    declare @test-2 table (id nvarchar(20),name varchar(10),fat int)

    insert into @test-2 (id,name,fat) values(1,'aa',10)

    insert into @test-2 (id,name,fat) values(1,'aa',10)

    insert into @test-2 (id,name,fat) values(1,'aa',10)

    insert into @test-2 (id,name,fat) values(2,'bb',20)

    select id,name,SUM( distinct fat) fat from @test-2

    group by id,name

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

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