2016-09-25 100 views
0

我有一個名爲文本的列,另一個名爲「類別」,有三個值「正面」,「負面」,「中性」。如何計算sql中列中值的數量的百分比?

如何計算類別中每個文本值的百分比?例如,如果我有3行,1行是正數,1行是負數,1行是中性,那麼查詢會產生33%正數33%負數和33%中性數?

這是我到了舞臺......

SELECT COUNT(category), category FROM tweets GROUP BY category 

回答

2

一種方式做到這一點

select category, count, count/total percent 
    from 
    (
    select category, count(category) count 
     from tweets 
    group by category 
) c JOIN (
    select count(*) total 
     from tweets 
) t 

輸出:

 
+----------+-------+---------+ 
| category | count | percent | 
+----------+-------+---------+ 
| negative |  1 | 0.3333 | 
| neutral |  1 | 0.3333 | 
| positive |  1 | 0.3333 | 
+----------+-------+---------+ 

...是否有可能? o只返回33%而不是0.3333?

select category, count, round(count/total * 100) percent 
    from 
    (
    select category, count(category) count 
     from tweets 
    group by category 
) c JOIN (
    select count(*) total 
     from tweets 
) t 
 
+----------+-------+---------+ 
| category | count | percent | 
+----------+-------+---------+ 
| negative |  1 |  33 | 
| neutral |  1 |  33 | 
| positive |  1 |  33 | 
+----------+-------+---------+ 

如果你想添加%可以用做concat(round(count/total * 100), '%')但我強烈建議在客戶端代碼做(任何一種格式)。

+0

感謝您的答案@peterm是否有可能只返回33%而不是0.3333? –

+0

太好了,謝謝@peterm –

0

只是一個小修改您的當前查詢:

SELECT COUNT(category)/COUNT(*), category FROM tweets GROUP BY category 
+0

'COUNT(category)/ COUNT(*)'總是會返回'1',假設'category'不包含空值 – peterm

+0

確認,你說得對。 – kiastu

1

作爲一個說明,我覺得這是更簡單地使用一個單一的子查詢寫着:

select t.category, count(*)/t.total,  -- number 
     concat(100 * count(*)/t.total, '%') -- string 
from tweets t join 
    (select count(*) as total) t 
group by category; 

如果你知道有隻有三個類別,我把它們放在一行:

select avg(category = 'positive') as p_positive, 
     avg(category = 'negative') as p_negative 
     avg(category = 'neutral') as p_neutral 
from tweets t; 

這q uery使用MySQL特性將布爾表達式視爲數字上下文中的整數,「1」爲true,「0」爲false。