MySQL Calculating percentage of two aliases

时间:2017-06-19 13:59:56

标签: mysql sql

I have managed to count what i needed and now im wondering how i could present the percantage ratio of two aliases.

SELECT c.fullname, COUNT( DISTINCT cc.userid ) AS  'calc1', COUNT( DISTINCT sst.id ) AS  'calc2'
FROM mdl_course c
INNER JOIN mdl_course_completions cc ON c.id = cc.course
INNER JOIN mdl_scorm s ON s.course = c.id
INNER JOIN mdl_scorm_scoes_track sst ON s.id = sst.scormid
INNER JOIN mdl_user u ON u.id = sst.userid
WHERE timecompleted IS NOT NULL 
AND sst.element =  'x.start.time'
GROUP BY c.fullname
ORDER BY  `calc2` DESC  

I've tried concat(round(( SELECT('Calc1')/SELECT('Calc2') * 100 ),2),'%') AS percentage but it doesnt work

Query representation

fullname  calc1 calc2
Something1  29    92
Something2  16    81
Something3  30    75

2 个答案:

答案 0 :(得分:1)

You can try below query:

select fullname, calc1, calc2, (calc1*100/calc2) per_ration from
( SELECT c.fullname, COUNT( DISTINCT cc.userid ) AS  'calc1', COUNT( DISTINCT sst.id ) AS  'calc2'
FROM mdl_course c
INNER JOIN mdl_course_completions cc ON c.id = cc.course
INNER JOIN mdl_scorm s ON s.course = c.id
INNER JOIN mdl_scorm_scoes_track sst ON s.id = sst.scormid
INNER JOIN mdl_user u ON u.id = sst.userid
WHERE timecompleted IS NOT NULL 
AND sst.element =  'x.start.time'
GROUP BY c.fullname
ORDER BY  `calc2` DESC ) as temp_tab;

答案 1 :(得分:1)

SELECT c.fullname, COUNT( DISTINCT cc.userid ) AS  'calc1', COUNT( DISTINCT sst.id ) AS  'calc2',
round(COUNT( DISTINCT cc.userid )/COUNT( DISTINCT sst.id ) )*100),2) as result
FROM mdl_course c
INNER JOIN mdl_course_completions cc ON c.id = cc.course
INNER JOIN mdl_scorm s ON s.course = c.id
INNER JOIN mdl_scorm_scoes_track sst ON s.id = sst.scormid
INNER JOIN mdl_user u ON u.id = sst.userid
WHERE timecompleted IS NOT NULL 
AND sst.element =  'x.start.time'
GROUP BY c.fullname
ORDER BY  `calc2` DESC