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-13 00:28:33
Message-ID: CABx31i5XhBMdCG1epRo+1MOSJfwqefUgYQ=mxkr-zaW63uGsSw@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?

num_ads | NorthEast | NorthWest | SouthEast | SouthWest | Middle of Nowhere
---------+-----------+-----------+-----------+-----------+-------------------
1 | 3895 | 3873 | 3898 | 3915 | 0
Thanks.

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message David Johnston 2013-04-13 03:26:05 Re: pivot query with count
Previous Message Tony Capobianco 2013-04-12 21:14:28 pivot query with count