Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

So berechnen Sie den Prozentsatz mit einer SQL-Anweisung

  1. Am effizientesten (mit over()).

    select Grade, count(*) * 100.0 / sum(count(*)) over()
    from MyTable
    group by Grade
    
  2. Universell (jede SQL-Version).

    select Grade, count(*) * 100.0 / (select count(*) from MyTable)
    from MyTable
    group by Grade;
    
  3. Mit CTE am wenigsten effizient.

    with t(Grade, GradeCount) 
    as 
    ( 
        select Grade, count(*) 
        from MyTable
        group by Grade
    )
    select Grade, GradeCount * 100.0/(select sum(GradeCount) from t)
    from t;