[英]mySQL Query Count Distinct and Percentage
我在創建查詢時會遇到麻煩,該查詢將報告按區域內區域分組的用戶的培訓完成情況。 對於一個培訓課程,報告需要針對每個地區顯示
輸出報告應該看起來像這樣(沒有句點):
區.........分配.......完成....%
阿肯色.......... 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子句中的“ District”替換了一個地區值(例如阿肯色州),則可以獲取該地區的正確值。 但是,我需要找到每個區域的所有地區並計算地區的值。 這只是我要為其創建查詢的區域之一。
兩個關鍵問題:
建議? 提前感謝你的幫助!!!
據我所知,您可以根據需要和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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.