查询以跨多列计数项目

时间:2015-02-01 11:23:58

标签: sql postgresql aggregate-functions

我有一张桌子:

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     |

有人可以给我一个正确的查询。

3 个答案:

答案 0 :(得分:2)

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

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

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

你应该考虑一个正确的一对多关系。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

另一个这样做

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