2014-07-18 85 views
0

我有一個MySQL表如何在一個查詢中執行兩次COUNT(*)提取?

id | string 
------------------------------ 
1 | one, two, three 
2 | two, three, five 
3 | one, three, four 
4 | three, five 
5 | one, two, three 
6 | two, three, five 
7 | one, three, four 
8 | one, three, five 
9 | two, three, four, five 
10 | one, two, three, five 

和我想獲取包含子three在列string元素的比例。我可以很容易地執行兩個查詢,並手動將它們劃分:

SELECT COUNT(*) FROM `table` WHERE `string` LIKE '%three%' 

和除以

SELECT COUNT(*) FROM `table` 

但我怎麼可能只用一個查詢執行呢?

回答

1

可以使用SUM與IF給予1或0括號內: -

SELECT SUM(IF(`string` LIKE '%three%', 1, 0))/COUNT(*) 
FROM `table` 
+0

是的,這個作品很有魅力! –

0

試試這個。

select sum(case when string like '%three%' then 1 else 0 end)/count(*) from table. 
+0

不返回正確的結果(與執行兩個查詢並手動將一個查詢分開)。這個查詢返回'0.0000'。 –

+0

DISTINCT不需要在這裏 – Kickstart

+0

編輯我的答案,請檢查它。 –

0
select sum(find_in_set('three', replace(`string`, ' ', '')) > 0) * 100/count(*) as percentage 
from your_table 

但是,你應該考慮改變你的表的設計。永遠不要永遠不要將多個值存儲在一列中!

+1

對於當前數據形式的字符串字段失敗。 –

+0

感謝您的提示。現在修復。 –

+0

@juergend感謝關於糟糕桌子設計的建議。該表是執行ETL過程的OLAP中間表。我只想做一些預先計算。 –

1

選擇與if條件,其中如果條件爲真,則返回1其他明智0。這裏count(*)返回總數或記錄。

SELECT (SUM(IF(`string` LIKE '%three%', 1, 0)) * 100)/COUNT(*) 
FROM `table` 
+0

它返回什麼,你想要什麼? – Sadikhasan

+0

對不起,困惑了一些答案。這會返回正確的結果。 –

+0

是的,我仍然在比較結果(尤其是表現時間)。 –