我在创建一个查询时遇到问题,该查询将报告按区域内按地区分组的用户的培训完成情况。对于一个培训课程,报告需要为每个区域显示
输出报告应如下所示(没有句点)。:
区.........分配.......完成....%
阿肯色.......... 20 .............. 15 ............... 75%
伊利诺伊............... 80 .............. 80 ............... 100%
爱荷华................. 10 ............... 8 ............ ..... 80%
密歇根.......... 30 .............. 20 ................ 66%
这是我尝试使用的SQL查询
Select mytable.district as District,
(Select Count(Distinct mytable.user_id)
From mytable
Where mytable.district = District AND
mytable.training_title = 'My Course') As 'Assigned',
(Select Count(Distinct mytable.user_id)
From mytable
Where mytable.training_status = "Completed" AND
mytable.district = District AND
mytable.training_title = 'My Course') as 'Completed',
Concat(Round(100 * (Select Count(Distinct mytable.user_id)
From mytable
Where mytable.training_status = "Completed" AND
mytable.district = District AND
mytable.training_title = 'My Course') / (Select Count(Distinct mytable.user_id)
From mytable
Where
mytable.district = District AND
mytable.training_title = 'My Course'),0 ),"%") as '%'
From mytable
Where mytable.region = 'Midwest'
Group by District
它根本不起作用。但是,如果我在WHERE子句中将其中一个区域值(例如阿肯色州)替换为“区域”,我可以获得该区域的正确值。但是我需要找到每个地区的所有地区并计算地区的价值。这只是我需要为其创建查询的区域之一。
两个关键问题:
连连呢?在此先感谢您的帮助!!!
答案 0 :(得分:1)
据我所见,您可以根据需要和GROUP BY
分区进行总结。子查询将处理重复的行。
SELECT
district,
COUNT(*) Assigned,
COUNT(CASE WHEN training_status='Completed' THEN 1 END) Completed,
CONCAT(COUNT(CASE WHEN training_status='Completed' THEN 1 END) /
COUNT(*) * 100, '%') `%`
FROM (
SELECT DISTINCT * FROM mytable
WHERE mytable.region = 'Midwest'
AND mytable.training_title = 'My Course') z
GROUP BY district;