Mysql - sum的输出作为单个表中一个字段中的一行

时间:2014-07-20 12:58:34

标签: php mysql pivot alias

我的陈述是这样的:

SELECT, id, Subject, score, fm
FROM(
SELECT id, Subject, SUM( score )/SUM(mm)*100 AS score,   
SUM(mm) as fm,
SUM(CASE WHEN enna IN ('test')
            THEN (score)
        END)/SUM(CASE WHEN enna IN ('test')
            THEN (mm)
        END)*100 AS scoreb
FROM table WHERE id ='2' AND Year='2014' 
AND enna = 'exam'  
GROUP BY Subject)r;

SQL FIDDLE HERE

如何将test作为主题之一并在相应的行中如何将scoreb作为字段score1中的行之一。我一直在谷歌搜索,找不到任何线索。 我没有足够的声誉可以上传到这里,所以我上传了预期的输出

enter image description here

2 个答案:

答案 0 :(得分:1)

我认为最简单的方法是使用union all

SELECT id, Subject, score, mm as fm
FROM table
WHERE id = '2' AND Year='2014' AND enna = 'exam'  
UNION ALL
SELECT id, 'test' as Subject, SUM(score) as score,
       SUM(score)/SUM(mm)*100 AS fm
FROM table
WHERE id = '2' AND Year='2014' AND enna = 'test' ;

顺便说一句,我没有得到fm的计算结果。查询中的计算与您显示的结果不同。但这很容易调整。

答案 1 :(得分:0)

试试这个。

SQL QUERY

SELECT id,Subject,MAX(Score) AS 'Score',MAX(mm) AS 'fm'
FROM tbl1
GROUP BY Subject
UNION ALL
(SELECT distinct id, 'test' AS Subject,
(SELECT SUM(score) AS 'score' FROM
(SELECT DISTINCT Score FROM tbl1 WHERE enna='test')t1) ,
(SELECT SUM(mm) AS 'fm' FROM
(SELECT DISTINCT mm FROM tbl1 WHERE enna='test')t2)
FROM tbl1
WHERE enna = 'test') ;

SQL FIDDLE HERE