SQL帮助(加入,转置?)

时间:2016-05-05 20:21:45

标签: sql

请参阅附图。我有3个表 - Region,Month和Customer。我想得到一个像Result表一样的表。怎么实现呢?不是一个SQL专家。任何帮助表示赞赏。 enter image description here

2 个答案:

答案 0 :(得分:1)

尝试条件聚合:

select m.month,
       sum(case when c.regionid = 1 then 1 else 0 end) as north,
       sum(case when c.regionid = 2 then 1 else 0 end) as south,
       sum(case when c.regionid = 3 then 1 else 0 end) as east,
       sum(case when c.regionid = 4 then 1 else 0 end) as west
from region r
cross join month m
left join customer c on c.regionid = r.regionid and c.monthid = m.monthid
group by m.monthid, m.month

答案 1 :(得分:0)

下面是如何使用PIVOT(在SQL Server中)执行此操作。刚看到你使用的是PostgreSQL,我认为它没有PIVOT,但你可以使用CROSSTAB。以下是一些例子: http://www.postgresql.org/docs/9.1/static/tablefunc.html https://gist.github.com/romansklenar/8086496

以下代码的rextester链接:http://rextester.com/VRZ32719

WITH REGION(regionid,  region)
    AS (select 1, 'North' union all
        select 2, 'South' union all
        select 3, 'East'  union all
        select 4, 'West' 
       )
,
CUSTOMER(customerid, regionid, monthid)
AS (select 1,1,1  union all
    select 2,1,12 union all
    select 3,2,3  union all
    select 4,3,4  union all
    select 5,4,3  union all
    select 6,4,10 union all
    select 7,2,2  union all
    select 7,2,2  union all
    select 8,3,1  union all
    select 9,2,3
   )
,
MONTH(monthid, month)
AS (select 1,  'Jan' union all
    select 2,  'Feb' union all
    select 3,  'Mar' union all
    select 4,  'Apr' union all
    select 5,  'May' union all
    select 6,  'Jun' union all
    select 7,  'Jul' union all
    select 8,  'Aug' union all
    select 9,  'Sep' union all
    select 10, 'Oct' union all
    select 11, 'Nov' union all
    select 12, 'Dec'
   )

select MONTH as ' ', NORTH, SOUTH, EAST, WEST from
   (select m.month, r.region, c.customerid
    FROM CUSTOMER c
     JOIN REGION r
      ON c.regionid = r.regionid
    FULL OUTER JOIN MONTH m
      ON c.monthid = m.monthid
    ) as a
   pivot
   ( count([customerid])
     for [region] in ([NORTH],[SOUTH],[EAST],[WEST])
    ) pivot_table
;