查询以跨多个列计算项目

Query to count items across multiple columns

我有一个table:

ID | fish1 | fish2 | fish3 |
1  | shark | dolfy | whale |
2  | tuna  | shark | dolfy |
3  | dolfy | shark | tuna  |
4  | dolfy | tuna  | shark |

查询结果为:

fish  | count |
shark | 4     |
tuna  | 3     |
dolfy | 4     |
whale | 1     |

谁能给我一个正确的查询。

您需要在非规范化 table 上创建规范化视图:

select fish, 
       count(*)
from (
  select fish1 as fish from the_table
  union all
  select fish2 from the_table
  union all
  select fish3 from the table
) t
group by fish

一般来说,这样存储数据不是个好主意(带编号的列通常表示设计不当)。

您应该考虑适当的一对多关系。

select fish, count (id)
from
(
SELECT fish1 as fish, id from my_table
union all
SELECT fish2 as fish, id from my_table
union all
SELECT fish3 as fish, id from my_table
) A
group by fish

另一种做法

select 'shark' as fish, count(case when fish1='shark' then 1 end)+count(case when fish2='shark' then 1 end)+
        count(case when fish3='shark' then 1 end) count from yourtable
union all
select 'tuna', count(case when fish1='tuna' then 1 end)+count(case when fish2='tuna' then 1 end)+
        count(case when fish3='tuna' then 1 end) from yourtable
union all
select 'dolfy', count(case when fish1='dolfy' then 1 end)+count(case when fish2='dolfy' then 1 end)+
        count(case when fish3='dolfy' then 1 end) from yourtable
union all
select 'whale',count(case when fish1='whale' then 1 end)+count(case when fish2='whale' then 1 end)+
        count(case when fish3='whale' then 1 end) from yourtable