sql >> Databasteknik >  >> RDS >> PostgreSQL

Postgresql Flera antal för en tabell

du kan använda case i det här fallet -

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

Det borde lösa ditt problem

@S T Mohammed,För att få en sådan typ kan vi helt enkelt använda using efter group eller where skick i yttre fråga, enligt nedan -

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


  1. Laravel tillhör att kasta odefinierat fel

  2. Databasdistribution med uppdateringar

  3. SQL - Operand-datatypen datetime2 är ogiltig för subtractoperator

  4. Korrekt sätt att förhindra dubbletter av poster med MySQL eller PHP