开发者

Count the number of times a string occurs in a row with the type SET

开发者 https://www.devze.com 2022-12-20 13:10 出处:网络
My database has got four columns: one, two, three and four each one has the type SET(\'a\',\'b\',\'c\',\'d\').

My database has got four columns: one, two, three and four each one has the type SET('a','b','c','d').

I want to know how many times a, b, c and d occurs in each column.

I guess I could do something like this

SELECT
(SELECT COUNT(*) FROM database as d WHERE d.a = 'one') AS one,
(SELECT C开发者_StackOverflow中文版OUNT(*) FROM database as d WHERE d.a = 'two') AS two,
(SELECT COUNT(*) FROM database as d WHERE d.a = 'three') AS three,
(SELECT COUNT(*) FROM database as d WHERE d.a = 'four') AS four
FROM database
LIMIT 1

four times which I know would work. Or I could fetch the entire result and count what's in the array.

Can I somehow do this more efficient?


select one,count(*) from db group by one
select two,count(*) from db group by two
etc


You can combine multiple counts in a single select using case and sum:

SELECT 
    sum(case when d.a = 'one' then 1 else 0 end) as SumAIsOne
,   sum(case when d.b = 'two' then 1 else 0 end) as SumBIsTwo
,   <other counts here>
FROM database
0

精彩评论

暂无评论...
验证码 换一张
取 消