pivot query with count - Mailing list pgsql-sql

From Tony Capobianco
Subject pivot query with count
Date
Msg-id CABx31i6ospJ=Cr-u2+O5VW=p0P8OXW_Jrswboh34bW7NKE5=7w@mail.gmail.com
Whole thread Raw
List pgsql-sql
The following is my code and results:
 
select '1' "num_ads",
     (case when r.region_code = 1000 then (
          select count(*) from  (
           select userid from user_event_stg2 where userid in (
            select userid from user_region where region_code = 1000)
             and messagetype = 'impression' group by userid
              having count(userid) = 1) as foo) else 0 end) as "NorthEast",
     (case when r.region_code = 2000 then (
          select count(*) from  (
           select userid from user_event_stg2 where userid in (
            select userid from user_region where region_code = 2000)
             and messagetype = 'impression' group by userid
              having count(userid) = 1) as foo) else 0 end) as "NorthWest",
     (case when r.region_code = 3000 then (
          select count(*) from  (
           select userid from user_event_stg2 where userid in (
            select userid from user_region where region_code = 3000)
             and messagetype = 'impression' group by userid
              having count(userid) = 1) as foo) else 0 end) as "SouthEast",
     (case when r.region_code = 4000 then (
          select count(*) from  (
           select userid from user_event_stg2 where userid in (
            select userid from user_region where region_code = 4000)
             and messagetype = 'impression' group by userid
              having count(userid) = 1) as foo) else 0 end) as "SouthWest",
     (case when r.region_code = 5000 then (
          select count(*) from  (
           select userid from user_event_stg2 where userid in (
            select userid from user_region where region_code = 5000)
             and messagetype = 'impression' group by userid
              having count(userid) = 1) as foo) else 0 end) as "Middle of Nowhere"
from user_region u, region r
where u.region_code = r.region_code
group by r.region_code;
 
num_ads | NorthEast | NorthWest | SouthEast | SouthWest | Middle of Nowhere
---------+-----------+-----------+-----------+-----------+-------------------
 1       |         0 |         0 |      3898 |         0 |                 0
 1       |      3895 |         0 |         0 |         0 |                 0
 1       |         0 |      3873 |         0 |         0 |                 0
 1       |         0 |         0 |         0 |      3915 |                 0
 
How can I get this output on to a single line?

Thanks.

pgsql-sql by date:

Previous
From: Simon Riggs
Date:
Subject: Re: Clarity on how LOCK interacts with INHERIT
Next
From: Tony Capobianco
Date:
Subject: pivot query with count