SUM multiple Columns

  • I was wondering if I could get some help with a query. I am using SQL 2008 and have a temporary table named RESULTS that contains 4 columns needing to be totaled, with those totals grouped by LISTINGID. The query I have below produces the correct result for ViewProperty, but the rest come back as 0(zero). I don't understand why is it requiring me to list all the other fields in the Group By clause when ListingID is the only field I want to group by. Can someone please tell me what I am doing wrong and how to get the correct totals on the other fields?

    Thanks!

    SELECT ListingID,StreetAddress, City, [State], SUM(ViewProperty) as ViewProperty, SUM(EmailAgent) as EmailAgent, SUM(AgentWebsite) as AgentWebsite, SUM(PDFFlyer) as PDFFlyer, SUM(Directions) as Directions

    FROM Results

    GROUP BY ListingID,StreetAddress, City, [State], ViewProperty, EmailAgent, AgentWebsite, PDFFlyer, Directions

    HAVING ViewProperty >0

    ORDER BY ViewProperty Desc

  • Because you're selecting these columns directly: ListingID,StreetAddress, City, [State]

    They will need to be in the group by clase. Emaliagent and the rest shouldn't be. Think select distinct. Anything not being manipulated across rows to a single result needs to grouped by so each group is unique. If you just want listingID, only include listingID and the rest of the SUM()s.

    As to why you're getting 0s... The HAVING clause kicks in AFTER the aggregations are done, so if the other sums are positive while viewproperty is 0, and 0 when viewproperty is positive, you won't see the results. Once you fix up the group by clause as well you should clear up most of your issues. Otherwise, we'd need to see the tabledefs and sample data to puzzle that out. See the first link in my sig for help if you need it.


    - Craig Farrell

    Never stop learning, even if it hurts. Ego bruises are practically mandatory as you learn unless you've never risked enough to make a mistake.

    For better assistance in answering your questions[/url] | Forum Netiquette
    For index/tuning help, follow these directions.[/url] |Tally Tables[/url]

    Twitter: @AnyWayDBA

  • Hi Craig,

    Thank you for your help! My problem turned out to be "HAVING ViewProperty >0", which turned out to a redundant step in my process since the RESULTS table will never conatain a property that has not been viewed. My new query (posted below) is now giving the correct results and totals.

    Thanks for pointing me in the right direction!

    SELECT ListingID,StreetAddress, City, [State], SUM(ViewProperty) as ViewProperty, SUM(EmailAgent) as EmailAgent, SUM(AgentWebsite) as AgentWebsite, SUM(PDFFlyer) as PDFFlyer, SUM(Directions) as Directions

    FROM Results

    GROUP BY ListingID,StreetAddress, City, [State]

    ORDER BY ViewProperty Desc

Viewing 3 posts - 1 through 2 (of 2 total)

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