2012-01-18 59 views
0

我在我的表中有type列,type列值是HOTNOT。從那我想要顯示HOTNOT列的值在一行中。如何顯示兩行中的一行

表1

Period ID Total 

11/2011 101 250 
12/2011 102 350 
11/2011 103 450 
.... 

表2

Period ID Type Value 

11/2011 101 NOT 500 
11/2011 101 HOT 200 
12/2011 102 NOT 300 
12/2011 102 HOT 200 
.... 

我想顯示在一個行型(HotNot

預期輸出

Period ID NOT HOT Total 

11/2011 101 500 200 250 
12/2011 102 300 200 350 
11/2011 103 300 400 450 
.... 

如何進行查詢。

回答

3

如果我可以假設,表1有(時期,ID)和表2的主鍵的(時期,ID,類型)主鍵,那麼你可以做:

select 
    t1.period 
    , t1.id 
    , t2n.value [not] 
    , t2h.value [hot] 
    , t1.total 
from 
    table1 t1 
    left join table2 t2n 
     on t1.period = t2n.period 
     and t1.id = t2n.id 
     and t2n.type = 'Not' 
    left join table2 t2h 
     on t1.period = t2h.period 
     and t1.id = t2h.id 
     and t2h.type = 'Hot' 

這將檢索來自表1的所有行以及它們對應的「不」和「熱」對應,分別對應於上面的t2n和t2h。

+0

+1。 '(ID)'可能是'Table1'的PK和'(ID,Type)''Table2',而'Table2.Period'是一個冗餘列,它只是複製'Table1.Period'。 – 2012-01-18 06:19:54

+0

@CD Jorgensen,它的工作,但在table2我有更多的時間然後table1,所以我想顯示所有的時間從表2和表2相同時期的表1 – Gopal 2012-01-18 08:08:27

+0

@RemoRose:嘗試完整連接,而不是左連接;爲了得到'period'和'id'的正確結果,請使用'CASE'表達式或'COALESCE()'。 – 2012-01-18 13:05:13

2

你試過這個嗎?

select base.period, base.id, sum(notchild.value) as notsum, sum(hotchild.value) as hotsum, base.total 
from table1 base 
left outer join table2 notchild 
    on base.period = notchild.period and base.id = notchild.id and notchild.type = 'NOT' 
left outer join table2 hotchild 
    on base.period = hotchild.period and base.id = hotchild.id and hotchild.type = 'HOT' 
group by base.period, base.id, base.total 
+0

您可能忘記在某處添加'notchild.type ='NOT''和'hotchild.type ='HOT''(很可能是加入條件)。 – 2012-01-18 06:16:16

+0

你是對的!對不起原來的海報。我會立即修改答案。 – 2012-01-18 07:20:48

0

您可以使用JOIN(檢查this)來做到這一點。加入你的兩張桌子,並在其上執行SELECT