質問

I have this code where it sums up the hours of the employee and uses rollup to get the total of the hours:

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

What I would like to do for my third column (Percent) is to divide the sum(actual) to the value of the total to get the percentage. But for that Percent column I don't need to get the Total Percent.

The total value is not constant to just 35.

Employee  |  Amount | Percent
    A     |   15    |  42.85
    B     |   10    |  28.57
    C     |   10    |  28.57
  Total   |   35    |

How can I do that? Here's the sqlfiddle: http://sqlfiddle.com/#!2/4543b/5

役に立ちましたか?

解決

This works as desired:

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

他のヒント

Perhaps a job best left to the logic tier of your application, but if you absolutely must do it in the data tier then you merely need to join your query with another that finds the overall total:

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
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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top