我有这张表:
+------------+-----------+--------+-------+------------+
| username | exam_code | module | value | percentage |
+------------+-----------+--------+-------+------------+
| aaaaa | x | 1 | 60 | - |
| aaaaa | x | 2 | 80 | - |
| aaaaa | x | 3 | 70 | - |
| bbbbb | x | 1 | 60 | - |
| bbbbb | x | 2 | 70 | - |
| bbbbb | x | 3 | 90 | - |
+------------+-----------+--------+-------+------------+
我想输入自己(使用php POST),模块的百分比
例如,如果我提出module 1 = 50%
,module 2 = 35%
,module 3 = 15%
(总数将是100)
它会将上一个表格变为:
+------------+-----------+--------+-------+------------+
| username | exam_code | module | value | percentage |
+------------+-----------+--------+-------+------------+
| aaaaa | x | 1 | 60 | 50 |
| aaaaa | x | 2 | 80 | 35 |
| aaaaa | x | 3 | 70 | 15 |
| bbbbb | x | 1 | 70 | 50 |
| bbbbb | x | 2 | 70 | 35 |
| bbbbb | x | 3 | 90 | 15 |
+------------+-----------+--------+-------+------------+
直到这一行,我可以用PHP
来做到这一点我想问的是,如何将此表(在输入的百分比字段之后)转换为此
+------------+----------+----------+----------+
| username | module 1 | module 2 | module 3 |
+------------+----------+----------+----------+
| aaaaa | 30 | 28 | 10.5 |
| bbbbb | 35 | 24.5 | 13.5 |
+------------+----------+----------+----------+
(解释)
+------------+----------+----------+----------+
| username | module 1 | module 2 | module 3 |
+------------+----------+----------+----------+
| aaaaa | (60x50%) | (80x35%) | (70x15%) |
| bbbbb | (70x50%) | (70x35%) | (90x15%) |
+------------+----------+----------+----------+
如何SELECT
(不创建表)来获取此表,只使用MySQL语法?
答案 0 :(得分:4)
这样的事情应该这样做。
SELECT username,
SUM(CASE WHEN module = 1 THEN value*percentage/100 END) as module1,
SUM(CASE WHEN module = 2 THEN value*percentage/100 END) as module2,
SUM(CASE WHEN module = 3 THEN value*percentage/100 END) as module3
FROM tablename
GROUP BY username