2013-11-25 59 views
0

我需要從一個選擇值傳遞到另一個,以完成計算並加入結果,但遇到此「with」子句子查詢的問題。如何傳遞值並加入WITH WITH子句的相關查詢?

這一個從第二查詢

WITH my_select (balance, type) As 
(
    select sum(amount_o-amount_h) as balance, type 
    from decret d 
    where d.idnumber = **loan_id** 
     and d.DATE_D <= '2013-10-31' 
     and type in (1,2,3,4,11,12,13,18,20,25) 
    group by type 
    having sum(amount_o-amount_h) <> 0 
) 
select sum(balance) FROM my_select //just returns client balance 

計算從提供的數字loan_id平衡,這一個選擇客戶端的數據,我想爲每個客戶端還增加了平衡在第一個查詢的計算結果。

SELECT *, /*balance*/ from clients 
where **loan_id** in (select LoanNum 
         from NumsFromEx) 

如何將它們結合在一起? (我已經簡化了一點點查詢顯示更乾淨)

回答

1

由於示例查詢,下面應該工作:

WITH cteBalances AS 
(
    SELECT loan_id, SUM(amount_o-amount_h) AS balance 
    FROM decret d 
    WHERE d.DATE_D <= '2013-10-31' 
     AND type IN (1,2,3,4,11,12,13,18,20,25) 
    GROUP BY loan_id 
) 
SELECT c.*, b.balance 
FROM clients c 
LEFT JOIN cteBalances b ON b.loan_id = c.loan_id 
WHERE loan_id IN (SELECT LoanNum 
        FROM NumsFromEx) 
+0

嗨,現在正在測試這一權利,但現在不知何故得到了太多的記錄,然後我應該。將更新。 –

+0

嗨祖魯它不清楚你試圖選擇什麼結果,這就是爲什麼我的查詢可能是錯誤的。如果您能夠向我展示一些簡單的示例數據,例如「decret」和「clients」,然後根據這些數據看到的結果,那麼我最簡單的方法就是給你提供建議。 – OGHaza

+0

我很驚訝,它會給你太多的記錄,但它應該給你每個客戶的貸款'loan_id'在'NumsFromEx' – OGHaza