简体   繁体   中英

How to show Null Value when using SUM Function in SQL Server

I have issue with my script in SQL Server, i need to show Total of 3 Columns with NULL Values我的查询

here is my query:

SELECT 
    Bucket,
        (SELECT SUM (OutstandingPrincipal)  FROM example
        WHERE [status] = 'Covid')
    AS Covid,
        (SELECT SUM (OutstandingPrincipal) FROM example
        WHERE [status] LIKE '%Disbu%')
    AS Disburs_After,
        (SELECT SUM (OutstandingPrincipal) FROM example
        WHERE [status] = 'Non Covid')
    AS Non_Covid
FROM example
WHERE Bucket IS NOT NULL
GROUP BY 
    Bucket

how is it possible? thanks in advance

If I'm understanding your data correctly, no need for all those subqueries, you can just use conditional aggregation :

select bucket,
       sum(case when status = 'Covid' then OutstandingPrincipal end) as covid,
       sum(case when status like '%Disbu%' then OutstandingPrincipal end) as Disburs_After,
       sum(case when status = 'Non Covid' then OutstandingPrincipal end) as Non_Covid
from example
where bucket is not null
group by bucket

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