简体   繁体   中英

How can I use having clause outside the subquery?

List item

I attached my query below and I need to filter the data based on below condition. The output is display only when the parameter is passed from the respective table.

 SELECT 
    (SELECT 'Static Field') AS account_type,
    (SELECT 
            COALESCE(SUM(ln.amount), 0)
        FROM
             ln
        WHERE
                AND ln.brch_id = $P{PARA_ID}
                AND ln.date < $P{PARAM_FROM_DATE}
                AND $P{PARA_Account_Type} = 'Static Field') AS debit_amount,
    (SELECT 
            COALESCE(SUM(pd.paid_amount), 0)
        FROM
         pd,
             ln
        WHERE
            pd.loan_id = ln.id AND ln.brch_id = $P{PARA_ID}
                AND pd.paid_date < $P{PARAM_FROM_DATE}
                AND $P{PARA_Account_Type} = 'Static Field') AS credit_amount
    having 
    account_type = 'Static Field'

Output should be: I expect the sum of the values based on above different condition only when the respective parameter is passed if it does not passed the respective parameter it will not display the row

Your query is interesting because it is a SELECT without a FROM and that's why you cannot use a WHERE or a HAVING to filter.

When your query is a SELECT without any FROM it always returns exactly 1 record.

A quick fix is to just add a simple FROM with 1 row as follows to your query which then enables you to filter with a HAVING.

FROM  ( select 1 as justarow ) r
HAVING account_type = 'Static Field'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM