2017-07-14 351 views
0

例如,我有SQL - 查詢:如何在此查詢中使用子查詢的結果?

SELECT 
    (SELECT value->>"$[0].value" 
     FROM leads_fields 
     WHERE leads_fields.field_id = 244991 AND leads_fields.lead_id = leads.external_id) 
     as 'coefRL', 
    (SELECT value->>"$[0].value" 
     FROM leads_fields 
     WHERE leads_fields.field_id = 244943 AND leads_fields.lead_id = leads.external_id) 
     as 'coefWF' 

FROM leads 

而爲了獲得這些價值,我需要複製像這樣的第三子查詢這些請求的區別?

(
    (SELECT value->>"$[0].value" 
    FROM leads_fields 
    WHERE leads_fields.field_id = 244991 AND leads_fields.lead_id = leads.external_id) 
     - 
    (SELECT value->>"$[0].value" 
     FROM leads_fields 
     WHERE leads_fields.field_id = 244943 AND leads_fields.lead_id = leads.external_id) 
) as 'difference' 

或者有更實用的方法,例如(coefRL - coefWF)

+0

您已經嘗試了臨時表? –

回答

1

這是一個辦法做到這一點沒有一個第三子查詢...

SELECT coefRL, 
    coefWF, 
    coefRL-coefWF difference 
FROM 
    (SELECT 
    (SELECT value->>"$[0].value" 
    FROM leads_fields 
    WHERE leads_fields.field_id = 244991 
    AND leads_fields.lead_id = leads.external_id 
    ) AS 'coefRL', 
    (SELECT value->>"$[0].value" 
    FROM leads_fields 
    WHERE leads_fields.field_id = 244943 
    AND leads_fields.lead_id = leads.external_id 
    ) AS 'coefWF' 
    FROM leads 
) 
相關問題