2015-09-06 71 views
0

我終於得到這個代碼 MySQL的內部工作作爲一個單一的查詢,而不是2 SELECT查詢一起在PHP代碼的一個$ SQL行:獲得百分比SELECT查詢在PHP SQL行工作

SELECT count(*) from mytable into @AgentCount; 

SELECT area 
    , COUNT(area) AS thecount 
    , ROUND ((COUNT(*)/(@AgentCount) * 100), 1) AS percentage 
FROM mytable 
GROUP BY area 
ORDER BY thecount DESC LIMIT 50; 

此外,仍然無法弄清楚如何在ROUND中使用%符號,以使百分比出現爲53.3%(等等)。我比我開始時更近,但仍然沒有雪茄。

我很可能在這裏錯過了一些簡單的事情,但頭腦凍結了。

感謝您的解凍幫助。

-stucko

回答

0

使用concat函數添加%符號並使用交叉連接。

SELECT area 
    , COUNT(area) AS thecount 
    , concat(ROUND((COUNT(*)/AgentCount * 100), 1), '%') AS percentage 
FROM mytable 
    cross join 
     (SELECT count(*) AgentCount from mytable) t 
GROUP BY area 
ORDER BY thecount DESC LIMIT 50; 
+0

這工作,splash58 - 謝謝!在Stack Overflow上,你們這些人真的很快而且很有幫助。非常感謝。現在要弄清楚如何反轉PHP輸出的順序來顯示%AREA -stucko – stucko

+0

只是想通了。 -stucko – stucko

+0

很高興幫助。不客氣 – splash58

0
SELECT area 
    , COUNT(area) AS thecount 
    , concat(ROUND ((COUNT(*)/(total_count) * 100), 1),"%") AS percentage 
FROM mytable,(SELECT count(*) as total_count from mytable)temp 
GROUP BY area 
ORDER BY thecount DESC LIMIT 50; 
+0

感謝您的貢獻,海鷹! -stucko – stucko