pivot query with count

From: Tony Capobianco <tony(dot)capobianco1(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: pivot query with count
Date: 2013-04-12 21:14:28
Message-ID: CABx31i6ospJ=Cr-u2+O5VW=p0P8OXW_Jrswboh34bW7NKE5=7w@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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.

Browse pgsql-sql by date

  From Date Subject
Next Message Tony Capobianco 2013-04-13 00:28:33 pivot query with count
Previous Message Simon Riggs 2013-04-12 21:09:07 Re: Clarity on how LOCK interacts with INHERIT