如何计算最终总金额和百分比

时间:2018-09-18 09:42:02

标签: sql postgresql percentage postgresql-9.3

下面我有一个查询,查询学生使用的每种语言的第一语言总数

CTE

<ol>
  <li>
    Order received
  </li>
  <li>
    Order received
  </li>
  <li>
    Order received
  </li>
  <li>
    Order received
  </li>
  <li>
    Order received
  </li>
</ol>

查询

WITH Lang AS
(
    SELECT  
        language, 
        studentcount,
        SUM(Studentcount) AS total
    FROM    
        (SELECT 
             l.longtext AS language,
             COUNT(distinct s.studentnr) AS Studentcount
         FROM 
             student s
         JOIN
             pupil p on p.id = s.pupilid
         JOIN
             pupillanguage pl on pl.personid = p.id
         JOIN
             language l on l.id = pl.languageid
         GROUP BY 
             l.longtext
         ORDER BY 
             Studentcount DESC
        ) t 
    GROUP BY 
        language, Studentcount
)

现在我有1个主要问题,那就是分配学生的TOTAL SUM值。我需要这样做,以便可以在列中计算学生人数/总学生人数百分比。但是很明显,我的总价值并没有满足我的需求。

输出

SELECT initcap(language), Studentcount, total
FROM Lang 

UNION ALL

SELECT cast(count(language) as varchar(6)) ||' Languages', null, null
FROM Lang

预期输出:

    languages   students    total
    ------------------------------
    French        734        734
    Afrikaans      93         93
    Greek         117        117
    German         55         55
    Armenian      160        160
    Malaysian       5          5
    Danish         15         15
    American        5          5
    Swedish        24         24
    Bulgarian     1043      1043

如何计算最终的总和作为计算百分比的值

2 个答案:

答案 0 :(得分:1)

demo:db<>fiddle

您可以使用窗口功能(https://www.postgresql.org/docs/current/static/tutorial-window.html):

SELECT
    language,
    students,
    SUM(students) OVER () as total,
    students::decimal / SUM(students) OVER () * 100 as percentage 
FROM
--- <YOUR QUERY>

由于SUM(students) OVER ()子句中没有限制框,因此窗口函数OVER汇总了学生列的所有值

必须进行::decimal强制转换才能获得浮点除法(100/200 = 0.5),而不是整数除法(100/200 = 0)。

答案 1 :(得分:1)

您可以尝试以下操作

with t1 as (           
        SELECT l.longtext as language,
       count(distinct s.studentnr) as Studentcount    
            FROM student s
                join pupil p on p.id = s.pupilid    
                join pupillanguage pl on pl.personid = p.id
                join language l on l.id = pl.languageid    
            group by l.longtext
            order by Studentcount desc
        ) select language,Studentcount, sum(Studentcount) over() as total,
      (Studentcount::float/sum(Studentcount) over())*100 as percentage
      from t1