2011-11-16 177 views
1

我被困在SQL問題上,我幾乎可以肯定這很容易,但我找不到合適的答案。下面是這個例子。我想那些2個查詢組合:組合2個SQL查詢

SELECT 
    num_rata, SUM(val_imp*0.01) AS amount 
FROM table1 
WHERE 
    col1 <> 0 
    AND num_contract = 88 
GROUP BY num_rata 

返回類似:

1 215.00 
2 220.00 
3 210.00 
4 115.00 
5 315.00 

和:

SELECT 
    num_rata, SUM(val_ban*0.01) AS amount 
FROM table2 
WHERE 
    num_contract = 2988 
GROUP BY num_rata; 

示例結果集:

1 15.00 
2 615.00 
3 275.00 
4 285.00 
5 285.00 
6 275.00 
7 260.00 
8 215.00 
9 215.00 

作爲最後一個結果我想要一些東西e此:

1 215.00 15.00 
2 220.00 615.00 
3 210.00 275.00 
4 115.00 285.00 
5 315.00 285.00 
6   275.00 
7   260.00 
8   215.00 
9   215.00 

謝謝你的任何提示。

fabien。

回答

3

你可以使用一個工會或外部聯接 - 我寧願工會,像這樣:

SELECT num_rata, sum(val_imp)*0.01 imp_amount, sum(val_ban)*0.01 ban_amount 
from (SELECT num_rata, val_imp, 0 val_ban 
     FROM table1 
     WHERE col1 <> 0 AND num_contract = 88 
     UNION ALL 
     SELECT num_rata, 0 val_imp, val_ban 
     FROM table2 
     WHERE num_contract = 2988) v 
GROUP BY num_rata; 
+0

謝謝馬克,但對不起,我不明白...... – feub

+0

@feub,哪一點你不明白?另外,你是否嘗試過運行它(或者真實情況更復雜)? –

+0

例如,在'SELECT num_rata,val_imp,0 val_ban'中,我沒有得到語法'0 val_ban'。而'v'是一個錯字?謝謝。 – feub

0

可嘗試將這種做:

SELECT num_rata, (
    coalesce(
     (SELECT SUM(val_imp*0.01) FROM table1 t1 WHERE t1.num_rata = foo.num_rata) 
    ,0) 
) as col1, (
    coalesce(
     (SELECT SUM(val_ban*0.01) FROM table2 t2 WHERE t2.num_rata = foo.num_rata) 
    ,0) 
) as col2 FROM 
(
    (SELECT num_rata FROM table1 WHERE col1 <> 0 AND num_contract = 88) 
    UNION ALL 
    (SELECT num_rata FROM table2 WHERE num_contract = 2988) 
) as foo; 

我可能有語法錯誤(我從一所大學演講寫這個),不過這(或類似)應該做的伎倆。

1

我想這是你想要的東西:

select 
    t1.num_rata, 
    SUM(t1.val_imp*0.01) AS amount1, 
    SUM(t2.val_ban*0.01) AS amount2 
from 
    table1 t1 right outer join table2 t2 on t1.num_rata=t2.num_rata 
where 
    t1.col1<>0 and 
    t1.num_contract = 88 and 
    t2.num_contract = 2988 
GROUP BY t1.num_rata 
+1

我同在一處同意一個外連接問題,但我覺得它應該是一個正確的外連接,因爲她需要第二個表中的所有記錄。看到這裏的一些例子左外部和右外部連接:http://en.wikipedia.org/wiki/Join_%28SQL%29 – user998692

+0

我同意,謝謝...早上太早 - 需要更多的咖啡....: - )(修正了我上面的答案) –

+0

可能是一個完整的外連接。此外,您似乎假定某個表上的給定num_rata存在多個記錄的情況下,對於另一個表上的相同num_rata,將永遠不會有多於一條記錄 - 否則,SUM將被誇大。假設每個表都有自己唯一的ID字段,可以通過將SUM(t1.val_imp * 0.01)更改爲SUM(t1.val_imp * 0.01)/ COUNT(DISTINCT COALESCE(t2.id,1))來修復它。 ',val_ban反之亦然。 –