Postgresql Multiple counts for one table

前端 未结 3 1853
夕颜
夕颜 2021-01-30 10:56

From two columns in my table I want to get a unified count for the values in these columns. As an example, two columns are:

Table: reports

|   type           


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 11:37

    you can use case in this case -

    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
    

    It should solve your problem

    @S T Mohammed, To get such type we can simply use using after group or where condition in outer query, as below -

    select type, Home, school, work, cafe, friends, mall from (
    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
     )
     where home >0 and School >0 and Work >0 and cafe>0 and friends>0 and mall>0
    

提交回复
热议问题