Correlated subquery in WHERE clause

73 views Asked by At

Could someone help me with Correlated subquery in WHERE NOT EXISTS clause using below example of exercise, cause I am not sure how to write this subquery and how would this work in INGRES database.

Let's say we have pension plan members who set aside funds to save for retirement.

Money is being converted into units which are on member's registers in database

We have 2 tables:

Table A - registers status

Columns:
    subfund_id 
    units_blocked 
    register_number 
    subfund_flag -  this means wheather the register_number 
                        belongs to subfund - 0 means no, 1 means yes

Table B - funds and subfunds

columns
    subfund_id
    subfund_full_name

Lets say we want to display all subfund_id and subfund_full_name for which there is at least one registry with a balance of blocked units greater than zero

My idea is:

    SELECT
    subfund_id, subfund_full_name
FROM
    Table B as t02
WHERE subfund_flag = 1 AND NOT EXISTS (SELECT *
                FROM Table A as t01
                WHERE t01.subfund_id = t02.subfund_id
                AND  units_blocked = 0)

GROUP BY
    subfund_id, subfund_full_name
HAVING
    COUNT(DISTINCT register_number) >= 1

Thanks for help

0

There are 0 answers