簡體   English   中英

MySQL查詢計數的不同和百分比

[英]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”替換了一個地區值(例如阿肯色州),則可以獲取該地區的正確值。 但是,我需要找到每個區域的所有地區並計算地區的值。 這只是我要為其創建查詢的區域之一。

兩個關鍵問題:

  • 所有數據都存在於數據庫的一個表中。 我已經合並並從另一個數據庫導入了它。
  • 數據包含重復項,因此我必須使用Distinct從結果中消除重復項。

建議? 提前感謝你的幫助!!!

據我所知,您可以根據需要和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;

要使用進行測試的SQLfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM