2012-10-02 80 views
0

你好我已經下面的SQL查詢SQL連接多個表,從第三個表中的列沒有顯示

Select catalogid , numitems, allitems - numitems ignoreditems 
     from ( 
     select i.catalogid, 
     sum(case when (ocardtype in ('PayPal','Sofort') OR 
         ocardtype in ('mastercard','visa') and 
         odate is not null) then numitems 
         else 0 end) numitems, 
     sum(numitems) allitems 
     from orders o 
     join oitems i on i.orderid=o.orderid 
     join products T1 on T1.catalogid = i.catalogid 
     group by i.catalogid 
     ) X 

在最後一個加入的語句表產品包含8列,他們並不在查詢結果顯示,我只能看到列catalogid,numitems和ignoreditems,所以我做錯了什麼,如果我必須選擇這些列,以使他們出現我怎麼能用這種語法呢?

+0

爲什麼嵌套select使用?可能會選擇(allitems - numitems)? – Prasanna

+0

是的,只是爲了這樣做 – user1570048

回答

1
Select catalogid , numitems, allitems - numitems ignoreditems, X.c1,X.c2,X.c3,X.c4,X.c5,X.c6,X.c7,X.c8 
    from ( 
    select i.catalogid, 
    sum(case when (ocardtype in ('PayPal','Sofort') OR 
        ocardtype in ('mastercard','visa') and 
        odate is not null) then numitems 
        else 0 end) numitems, 
    sum(numitems) allitems , 
    T1.c1, T1.c2, T1.c3, T1.c4, T1.c5, T1.c6, T1.c7, T1.c8 
    from orders o 
    join oitems i on i.orderid=o.orderid 
    join products T1 on T1.catalogid = i.catalogid 
    group by i.catalogid, T1.c1, T1.c2, T1.c3, T1.c4, T1.c5, T1.c6, T1.c7, T1.c8 
    ) X 
1

你只是在查詢這三列。如果您希望產品中的列顯示在結果集中,只需將它們添加到select語句即可。您可以逐個添加它們,或者僅添加T1。*以查詢所有這些內容:

Select catalogid , numitems, allitems - numitems ignoreditems, X.columnName1, X.ColumnName2, X.* 
from ( 
select i.catalogid, 
sum(case when (ocardtype in ('PayPal','Sofort') OR 
ocardtype in ('mastercard','visa') and 
odate is not null) then numitems 
else 0 end) numitems, 
sum(numitems) allitems, 
-- This 
T1.ColumnName1, T1.ColumName2, ... 
--- or this way 
T1.* 
from orders o 
join oitems i on i.orderid=o.orderid 
join products T1 on T1.catalogid = i.catalogid 
group by i.catalogid 
) X