简体   繁体   English

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

[英]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 SQL此处

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 . 如何将测试用作主题之一,如何在对应的行中将scoreb用作字段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 : 我认为最简单的方法是使用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 . 顺便说一句,我没有得到fm的计算。 The calculation in the queries is different from the results you show. 查询中的计算与您显示的结果不同。 But that can easily be adjusted. 但这很容易调整。

Try this. 尝试这个。

SQL QUERY SQL查询

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 SQL此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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