将百分比列添加到MYSQL中的现有数据

时间:2011-05-20 21:58:43

标签: mysql

自今天早些时候以来,我有这个答案

SELECT  Users.full_name
        ,sum(total)
        ,sum(case when service < 49 then total else 0 end) AS Productive
FROM    time_report
        , users
WHERE   time_report.User = users.user_id
        AND date BETWEEN '2011-0502' AND '2011-05-11'
GROUP BY 
        User

这给了我以下数据,这就是我想要的

full_name   sum(total)  Productive

Cian Higgins    26  14

Wallace Ward    23  23

jason ward      42  33

Thomas Woods    72  53

Peter Jones     49  41

fintan corrigan 40  32

David Jones     35  27

January Jones   23  23

Joe Johnson     24  24

我想知道有没有办法在输出中添加一个名为percentage的aditional列,这将为我提供Round((Total/productive) * 100)的输出

我一直在努力解决这个问题。 我已经使用原始查询的输出创建了一个临时表,但我正在努力使用正确的语法来获取输入的百分比。

任何帮助表示感谢。

3 个答案:

答案 0 :(得分:4)

不幸的是,派生的列只能在ORDER BY中按名称使用。也就是说,您必须在SELECT列中复制它而不是能够说ROUND((Total/Productive) * 100)

SELECT  Users.full_name
        ,sum(total) AS Total
        ,sum(case when service < 49 then total else 0 end) AS Productive
        ,(ROUND(sum(total) / sum(case when service < 49 then total else 0 end)) * 100) AS Percentage
FROM    time_report
        , users
WHERE   time_report.User = users.user_id
        AND date BETWEEN '2011-0502' AND '2011-05-11'
GROUP BY User

答案 1 :(得分:2)

您可以通过将原始查询移动到FROM子句来避免重复聚合表达式。

SELECT full_name, Total, Productive, Round((Total/Productive) * 100) AS pcnt
FROM
(
SELECT  Users.full_name
    ,sum(total) As Total,
    ,sum(case when service < 49 then total else 0 end) AS Productive
 FROM    time_report
    , users
WHERE   time_report.User = users.user_id
    AND date BETWEEN '2011-0502' AND '2011-05-11'
GROUP BY 
    User
)a

答案 2 :(得分:0)

SELECT  Users.full_name
        ,sum(total)
        ,sum(case when service < 49 then total else 0 end) AS Productive
        ,(Round((sum(total)/sum(case when service < 49 then total else 0 end)) * 100)) AS Percent
...