我有这个代码,它总结了员工的工作时间,并使用汇总来获得总时数:
SELECT IFNULL(users, 'Total') AS Employee,
SUM(actual) AS Amount
FROM table1
WHERE name = "ProjectName"
GROUP BY users
WITH ROLLUP
Employee | Amount
A | 15
B | 10
C | 10
Total | 35
我想为第三列(百分比)做的是将总和(实际)除以总计的值以获得百分比。 但对于那个百分比专栏,我不需要获得总百分比。
总值不会恒定到35。
Employee | Amount | Percent
A | 15 | 42.85
B | 10 | 28.57
C | 10 | 28.57
Total | 35 |
我该怎么做? 这是sqlfiddle:http://sqlfiddle.com/#!2/4543b/5
答案 0 :(得分:4)
这可以按照需要运行:
SET @project_name = 'ProjectName';
SELECT IFNULL(users, 'Total') AS Employee, SUM(actual) AS Amount,
IF(ISNULL(users), '', TRUNCATE(SUM(actual) / sum_table.amount_sum * 100, 2)
) AS Percent
FROM Table1
INNER JOIN (
SELECT SUM(actual) AS amount_sum
FROM Table1
WHERE name = @project_name
) AS sum_table
WHERE name = @project_name
GROUP BY users
WITH ROLLUP;
DEMO @ SQL Fiddle
答案 1 :(得分:1)
也许最好的工作留给你的应用程序的逻辑层,但如果你绝对必须在数据层中这样做,那么你只需要将查询与另一个查找整体总数的查询一起加入:
SELECT IFNULL(users, 'Total') AS Employee,
SUM(actual) AS Amount,
SUM(actual)/t.Total AS Percent
FROM Table1, (
SELECT SUM(actual) AS Total
FROM Table1
WHERE name = 'ProjectName'
) t
WHERE name = 'ProjectName'
GROUP BY users WITH ROLLUP
答案 2 :(得分:1)
SELECT if(users is NULL,'Total',users) as Employee, sum(actual) as Amount,
(CASE
WHEN users is not null THEN CAST(sum(actual)/sum.sumAmt * 100 as DECIMAL(10,2))
END) as Percent
FROM Table1, (SELECT sum(actual) as sumAmt FROM Table1
WHERE name = 'ProjectName') sum
WHERE name = "ProjectName"
GROUP BY users
WITH ROLLUP
<强> DEMO 强>