加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Postgresql一个表的多个计数

发布时间:2020-12-13 16:33:36 所属栏目:百科 来源:网络整理
导读:从我的表中的两列,我想得到这些列中的值的统一计数. 例如,两列是: 表:报告 | type | place | ----------------------------------------- | one | home | | two | school | | three | work | | four | cafe | | five | friends | | six | mall | | one | w
从我的表中的两列,我想得到这些列中的值的统一计数.
例如,两列是:

表:报告

|   type        |   place   |  
 ----------------------------------------- 
|   one         |   home    |  
|   two         |   school  |  
|   three       |   work    |  
|   four        |   cafe    |  
|   five        |   friends |  
|   six         |   mall    |  
|   one         |   work    |  
|   one         |   work    |  
|   three       |   work    |  
|   two         |   cafe    |  
|   five        |   cafe    |  
|   one         |   home    |

如果我做:
SELECT类型,count(*)从报表
按类型分组

我得到:

|   type        |   count   |  
-----------------------------  
|   one         |   4       |  
|   two         |   2       |  
|   three       |   2       |  
|   four        |   1       |  
|   five        |   2       |  
|   six         |   1       |

我试图得到这样的东西:(一个最右边的列,我的类型分组在一起,多个列与每个地方的计数值)
我得到:

|   type        |   home    |   school  |   work    |   cafe    |   friends |   mall    |  
-----------------------------------------------------------------------------------------  
|   one         |   2       |           |   2       |           |           |           |  
|   two         |           |   1       |           |   1       |           |           |  
|   three       |           |           |   2       |           |           |           |  
|   four        |           |           |           |   1       |           |           |  
|   five        |           |           |           |   1       |   1       |           |  
|   six         |           |           |           |           |           |   1       |

这将是像这样运行像上面一样的计数的结果:

SELECT type,count(*) from reports where place  = 'home'
group by type
SELECT type,count(*) from reports where place  = 'school'
group by type
SELECT type,count(*) from reports where place  = 'work'
group by type
SELECT type,count(*) from reports where place  = 'cafe'
group by type
SELECT type,count(*) from reports where place  = 'friends'
group by type
SELECT type,count(*) from reports where place  = 'mall'
group by type

这是否可能与postgresql?

提前致谢.

你可以在这种情况下使用案例 –
SELECT type,sum(case when place  = 'home' then 1 else 0 end) as Home,sum(case when  place  = 'school' then 1 else 0 end) as school,sum(case when  place  = 'work' then 1 else 0 end) as work,sum(case when  place  = 'cafe' then 1 else 0 end) as cafe,sum(case when  place  = 'friends' then 1 else 0 end) as friends,sum(case when  place  = 'mall' then 1 else 0 end) as mall
  from reports
 group by type

应该解决你的问题

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读