简体   繁体   中英

SQL Nested Select Statement

I have the following SQL Code which is not giving me my desired results.

SELECT
    POLICIES.CLIENTS_ID,
    POLICIES.CLIENTCODE,
    COUNT(POLICIES.POLICIES_ID) as [Total Policies],
    (
        SELECT 
            COUNT(POLICIES.POLICIES_ID) 
        FROM 
            POLICIES 
        WHERE 
            POLICIES.COVCODE = 'AUT'
    ) as [Auto Policies]

FROM
    POLICIES
    LEFT JOIN CLIENTS
        ON CLIENTS.CLIENTS_ID = POLICIES.CLIENTS_ID

WHERE
    POLICIES.CNR IS NULL

GROUP BY 
    POLICIES.CLIENTS_ID,
    POLICIES.CLIENTCODE

ORDER BY 
    POLICIES.CLIENTS_ID

I get a result like this:

ID  CODE    Total    Auto
3   ABCDE1  1        999999
4   ABCDE2  1        999999
5   ABCDE3  2        999999
6   ABCDE4  2        999999

I would like for the last column to COUNT the total auto policies that exists for that clientid rather than all of the auto policies that exist. I believe I need a nested select statement that somehow groups all like results on the clientid, but it ends up returning more than 1 row and throws the error.

If I add:

GROUP BY 
    POLICIES.CLIENTS_ID

I get:

Subquery returned more than 1 value. This is not permitted when the....

Any help would be appreciated greatly! Thank you

You can use a CASE statement to do this. Instead of your subquery in the SELECT clause use:

SUM(CASE WHEN POLICIES.COVCODE = 'AUT' THEN 1 ELSE 0 END) as [AUTO POLICIES]

As Martin Smith pointed out. If client_id has multiple client_codes then this will give you the count of records for each combination of client_id/client_code. If client_id is 1:1 with client_code then this will give you a count of records for each distinct client_id, which I suspect is the case from your example and question.

Unrelated: You have a LEFT JOIN to your Clients table, but you don't use your Clients table anywhere int he query. Consider removing it if you don't need to select or filter by any its fields, since it's just unused overhead.

如果您修改内部查询以使计数增加到类似该怎么办

SUM(CASE WHEN POLICIES.COVCODE = 'AUT' THEN 1 ELSE 0 END) as [Auto Policies]

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