Wednesday, September 19, 2012

How to calculate percentage with a SQL statement

  1. The most efficient (using over()).
    select Grade, count(*) * 100.0 / sum(count(*)) over()
    from MyTablegroup by Grade
  2. Universal (any SQL version).
    select Rate, count(*) * 100.0 / (select count(*) from MyTable)
    from MyTablegroup by Rate;
    
  3. With CTE, the least efficient.
    with t(Rate, RateCount) as ( 
        select Rate, count(*) 
        from MyTable
        group by Rate)
    select Rate, RateCount * 100.0/(select sum(RateCount) from t)
    from t;
    
http://stackoverflow.com/questions/770579/how-to-calculate-percentage-with-a-sql-statement

No comments:

Post a Comment