简体   繁体   中英

sql query with totals in the same query

select 
    grade, pro_abo as procUpper, pro_with as procMiddle, 
    pro_below as procLower, pro_insuf as procNa, 
    cum_abo as cumulativeUpper, cum_with as cumulativeMiddle, 
    cum_below as cumulativeLower, cum_insuf as cumulativeNa
from 
    (select distinct v.* 
     from M_VW v, m_info mi
     where v.id = mi.id and mi.id_ti = 1094574915) ;

The output of this query is

Grade       procUpper   procMiddle  procLower   procNa  cumulativeUpper cumulativeMiddle  cumulativeLower   cumulativeNa
HOD         100         100         100         4       100             100                 100             10
lecturer    100         100         100         10      100             100                 100             10
Professor   100         100         100         10      100             100                 100             10
RA          100         100         100         10      100             100                 100             10
PA          100         100         100         4       100             100                 100             10

I want to add totals at the bottom like ,

Grade       procUpper   procMiddle  procLower   procNa  cumulativeUpper cumulativeMiddle  cumulativeLower   cumulativeNa
HOD         100         100         100         4       100             100                 100             10
lecturer    100         100         100         10      100             100                 100             10
Professor   100         100         100         10      100             100                 100             10
RA          100         100         100         10      100             100                 100             10
PA          100         100         100         4       100             100                 100             10
Total       100%        100%        100%        38      100%            100%                100%            50

The 5th column and the last column doesnt have to have %.

The simplest method in this case is probably:

with t as (
      select grade, pro_abo as procUpper, pro_with as procMiddle, pro_below as procLower,
             pro_insuf as procNa, cum_abo as cumulativeUpper, cum_with as cumulativeMiddle, cum_below as cumulativeLower,
             cum_insuf as cumulativeNa
      from (select distinct v.*
            from M_VW v join
                 m_info mi
            where v.id = mi.id and mi.id_ti = 1094574915
         ) v
      )
select t.*
from t
union all
select NULL, sum(pro_abo), sum(pro_with), sum(pro_below), sum(pro_insuf), sum(cum_abo), sum(cum_with), sum(cum_below)
from t
order by grade nulls last;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM