2011-11-07 86 views
0

我試圖運行MySQL查詢並使用PHP來做到以下幾點:的行總數從每個GROUP BY

我需要組數據在列(GROUP BY),再算上(COUNT)的數量每組中的行。之後,我需要將給定組中的行數除以組的數量以獲得該組的流行度。

所以,如果我有一個表具有以下數據:

Version_Number 
1.1 
1.2 
1.1 
1.2 
1.2 
1.1 

I need the final output to be: 

1.1 50% 
1.2 50% 

回答

1

這是我最後做嘗試上述後:

$result = mysql_query("SELECT COUNT(*) AS nsites FROM table WHERE auth = '$auth'") or 
        die(mysql_error()); 
        $return_sites = mysql_fetch_array($result); 

       if (!$return_sites['nsites']) { 

       echo "..."; 

       } else { 

        $esult = mysql_query("SELECT * FROM table WHERE auth = '$auth' GROUP BY theme_version") or die(mysql_error()); 
        while($row = mysql_fetch_array($esult)){       

         $get_current_version = $row['theme_version']; 

         $vresult = mysql_query("SELECT COUNT(*) AS nversion FROM table WHERE auth = '$auth' AND theme_version = '$get_current_version'") or die(mysql_error()); 
         $version = mysql_fetch_array($vresult); 

         $percent = round($version['nversion']/$return_sites['nsites'] * 100); 

          echo "..."; 

        } 

       } 
0

事情是這樣的:

select v."Version_Number", count(v."Version_Number"),count(v."Version_Number")::float/(select count(v2."Version_Number")::float from versions v2)::float * 100::float 
from versions as v 
group by v."Version_Number" 
+0

這可能是錯的,我不認爲你可以加入這樣的選擇:\ – Louis

+0

那現在工作(從Postgres)你可能需要爲mysql感到遺憾。 – Louis

1

您可能需要調整這個爲MySQL(我通常在Oracle工作),但是:

SELECT 
    (count(*)/totalCount * 100) AS percentOfVersionedThings 
    , Version_Number 
FROM tableOfVersionedThings 
    INNER JOIN (SELECT count(*) as totalCount FROM tableOfVersionedThings) ON 1=1 
GROUP BY Version_Number 

如果這是甲骨文,我建議使用分析,但我不知道是否有在同等我SQL。這就是說,在你的情況下,一個簡單的子查詢應該可以解決問題,並且它應該可以在任何SQL數據庫上使用。