Postgresql Multiple counts for one table

前端 未结 3 1852
夕颜
夕颜 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条回答
  •  -上瘾入骨i
    2021-01-30 11:59

    Answer by praktik garg is correct, it is not necessary to use else 0:

    SELECT type, 
           sum(case when place  = 'home' then 1 end) as home,
           sum(case when  place  = 'school' then 1 end) as school,
           sum(case when  place  = 'work' then 1 end) as work,
           sum(case when  place  = 'cafe' then 1 end) as cafe,
           sum(case when  place  = 'friends' then 1 end) as friends,
           sum(case when  place  = 'mall' then 1 end) as mall
    FROM reports
    GROUP BY type
    

    You can also use the following even shorter syntax:

    SELECT type, 
           sum((place  = 'home')::int) as home,
           sum((place  = 'school')::int) as school,
           sum((place  = 'work' )::int) as work,
           sum((place  = 'cafe' )::int) as cafe,
           sum((place  = 'friends')::int) as friends,
           sum((place  = 'mall')::int) as mall
    FROM reports
    GROUP BY type
    

    This will work because boolean true is cast to 1 when condition is met.

提交回复
热议问题