2016-04-29 82 views
1

我有一個useriInterface,用於捕獲單選按鈕的點擊並根據所選值增加數據庫中的計數器。如何通過sql顯示輪詢結果

這一切工作正常。

我的問題是,如何顯示輪詢結果百分比值?

這是我的數據庫結構

CREATE TABLE `poll_results` (
    `name` varchar(50) DEFAULT NULL, 
    `count` int(11) DEFAULT NULL, 
    `modified_date` varchar(50) DEFAULT NULL 
) ENGINE=MyISAM DEFAULT CHARSET=latin1; 



Insert into poll_results (name,count,modified_date)values ('pollchoiceone' , 3 , now()); 
Insert into poll_results (name,count,modified_date)values ('pollchoicetwo' , 10 , now()); 
Insert into poll_results (name,count,modified_date)values ('pollchoicethree' , 7 , now()); 
Insert into poll_results (name,count,modified_date)values ('pollchoicefour' , 0 , now()); 

是否有可能實現通過一個選擇查詢?

http://sqlfiddle.com/#!9/e5e835/1

+0

將所期望的結果是什麼樣的? – Strawberry

回答

2

你可以cross join從表中查詢用凝聚票的整個數字,然後分兩個查詢。例如: -

SELECT  name, `count`, `count`/`total_count` * 100 AS percetnage 
FROM  poll_results 
CROSS JOIN (SELECT SUM(`count`) AS `total_count` 
      FROM poll_results) t 

SQLFiddle example

+0

很好的答案,非常感謝。 – Pawan

1

使用預建TOTAL_COUNT表另一種解決方案:

SELECT name, `count`, `count`/t.total_count * 100 AS percentage 
FROM poll_results, (select sum(`count`) AS total_count from poll_results) t 

SQL Fiddle