Computing the % of Total for a column

  • I want to compute the percent of the total that a row has.

     

    Example:

    NameSales% of Sales
    Bob2020%
    Frank1010%
    Charlie6060%
    Sally44%
    Jane66%
    Total100100%

    I am going to display this table in a web page, so I will be summing my totals using code, but the piece that I really want SQL to do is to compute the % column.  (I can loop through all of my returned records, total my column, then start back at the beginning to write the records out, but that seems like "cheating" to me.)

    To complicate matters, the "Name" field is actually a "Group By Department" statement that I am doing in the code.

    I was taking a quick lok at the "Compute" and "Compute By" statements in SQL help.  This seems like a cool feature to do Grouping on, displaying all of my details, breaking on certain fields, etc... 

    Can someone give me a quick and dirty sample of how to set one up?

    Thanks,

    Bryan Clauss

  • This is what I would do

     

    Select Name, Sales, round(100*Sales/TotalSales,0) [% os Sales]

    from

    (Select Department as Name, Sum(Amount) as Sales

    from SalesTable

    Group by Department ) dt1

    cross join (Select Sum(Amount) as TotalSales from SalesTable ) t


    * Noel

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

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