2012-05-18 101 views
1

在我目前的表我試圖根據COMP_NAME獲得列的平均值,以下是輸出後,選擇平均

"Comp_Name"   "No_of_Rows" "Column1_Avg" "Column2_Avg" "Column3_Avg" 
    "Company1 Pty Ltd" "291"   "39"   "60"   "0" 
    "Company1 Pty."  "1699"   "23"   "76"   "0" 
    "Company2 Ltd"  14335"   "6"    "82"   "10" 
    "Company2 "   "4335"   "60"   "8"    "2" 
    "Company3 Pty Ltd" "767"   "22"   "77"   "0" 
    "Company3"   "1628"   "16"   "82"   "1" 

是可以平均「的公司1私人有限公司」和「MySQL的命名列的值Company1 Pty。「 (和其他公司),但添加行數?

我的選擇查詢是下面,基本上它是基於一定的值計算平均值,並根據公司名稱分組可在表

SELECT Comp_Name,count(*) as No_of_Rows, 
    CAST( (COUNT(CASE WHEN Column1 < 500 then 1 else NULL end)/COUNT(mytable.ID)) * 100 AS CHAR(2))+'%' as Column1_Avg, 
    CAST( (COUNT(CASE WHEN (Column1 < 30000 AND Column1 > 500) then 1 else NULL end)/COUNT(mytable.ID)) * 100 AS CHAR(2))+'%' as Column2_Avg, 
    CAST( (COUNT(CASE WHEN (Column1 > 30000) then 1 else NULL end)/COUNT(mytable.ID)) * 100 AS CHAR(2))+'%' as Column3_Avg 
    FROM mytable 
    GROUP BY Comp_Name desc 

預期輸出:

"Comp_Name"   "No_of_Rows" "Column1_Avg" "Column2_Avg" "Column3_Avg" 
    "Company1"   "1990"   "31"   "68"   "0" 
    "Company2"   "18670"   ".."   ".."   "6" 
    "Company3"   "2395"   ".."   ".."   ".." 

我可以使用某種具有company_name列表的參考表並且它的替換?

回答

2

如果你想只取第一個字在你GROUP BY條款,你可以使用:

 
GROUP BY CASE LOCATE(' ', Comp_Name) WHEN 0 THEN Comp_Name ELSE LEFT(Comp_Name, LOCATE(' ', Comp_Name)) END 

然後,如果你想建立一個參考表,這樣的查詢應該是罰款:

 
SELECT DISTINCT Comp_Name, CASE LOCATE(' ', Comp_Name) WHEN 0 THEN Comp_Name ELSE LEFT(Comp_Name, LOCATE(' ', Comp_Name)) END AS Simple_Comp_Name 
FROM mytable 
ORDER BY Simple_Comp_Name 
+0

謝謝。我也試過INNER JOIN,似乎工作正常。 – Linus