Postgresql一个表的多个计数

前端之家收集整理的这篇文章主要介绍了Postgresql一个表的多个计数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
从我的表中的两列,我想得到这些列中的值的统一计数.
例如,两列是:

表:报告

  1. | type | place |
  2. -----------------------------------------
  3. | one | home |
  4. | two | school |
  5. | three | work |
  6. | four | cafe |
  7. | five | friends |
  8. | six | mall |
  9. | one | work |
  10. | one | work |
  11. | three | work |
  12. | two | cafe |
  13. | five | cafe |
  14. | one | home |

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

我得到:

  1. | type | count |
  2. -----------------------------
  3. | one | 4 |
  4. | two | 2 |
  5. | three | 2 |
  6. | four | 1 |
  7. | five | 2 |
  8. | six | 1 |

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

  1. | type | home | school | work | cafe | friends | mall |
  2. -----------------------------------------------------------------------------------------
  3. | one | 2 | | 2 | | | |
  4. | two | | 1 | | 1 | | |
  5. | three | | | 2 | | | |
  6. | four | | | | 1 | | |
  7. | five | | | | 1 | 1 | |
  8. | six | | | | | | 1 |

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

  1. SELECT type,count(*) from reports where place = 'home'
  2. group by type
  3. SELECT type,count(*) from reports where place = 'school'
  4. group by type
  5. SELECT type,count(*) from reports where place = 'work'
  6. group by type
  7. SELECT type,count(*) from reports where place = 'cafe'
  8. group by type
  9. SELECT type,count(*) from reports where place = 'friends'
  10. group by type
  11. SELECT type,count(*) from reports where place = 'mall'
  12. group by type

这是否可能与postgresql

提前致谢.

你可以在这种情况下使用案例 –
  1. 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
  2. from reports
  3. group by type

应该解决你的问题

猜你在找的Postgre SQL相关文章