简体   繁体   中英

Mysql - output of sum as one of the rows in one field in a single table

My statement goes like this:

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

How can I use test as one of the subject and in the corresponding row how can I put scoreb as one of the rows in field score1 . I have been googling and could not find any clue. I don't have enough reputation to upload here, so I have uploaded my expected output at

在此处输入图片说明

I think the easiest way is to use 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' ;

By the way, I don't get the calculation for fm . The calculation in the queries is different from the results you show. But that can easily be adjusted.

Try this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM