2016-05-05 8 views
0

添付の画像を参照してください。私は3つのテーブルを持っています - 地域、月、および顧客。私は結果テーブルのようなテーブルを取得したい。それを達成する方法? SQLの専門家ではありません。どんな助けもありがとうございます。 enter image description hereSQL Help(Join、transpose?)

+0

の質問では、スキーマ、スキーマのない画像。私たちの中にはファイアウォールの背後にいるものもあり、あなたの写真は見えません。 – WillardSolutions

+0

北、南、東、西の列はどこにありますか? – ryekayo

+0

@ryekayo - それはregionidにリンクされています。 – Dresden

答えて

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

m.monthid ascで注文を追加して1月から12月になるようにしてください。 – Dresden

+0

あなたの迅速な対応に感謝します。条件文の領域IDをハードコードする代わりに、Regionテーブルから領域のリストを動的に取得する方法はありますか? –

+0

残念ながらいいえ。 SQL Serverを使用している場合、動的クエリを実行できますが、他のrdbmsではわかりません。 –

0
以下

(SQL Serverで)PIVOTを使用してそれを行う方法です。ちょうど私がPIVOTを持っていないと信じているPostgreSQLを使っているのを見ましたが、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 
;