简体   繁体   中英

How to count different fields in a row in SQL

In my table I have a list of fields I want to count when they are not NULL.

For example, here are some rows and what I want to count in the end:

| locks | keys | boxes | what_I_want_count |
|   3   |   4  |   5   |     *12*          |
|   2   |   0  |   7   |     *9*           |
|   0   |   0  |   1   |     *1*           |

Any idea how to do this? I am using Postgresql (Redshift).

you can use coalesce() function then add your columns

select coalesce(locks, 0) + coalesce(keys, 0) +  coalesce(boxes, 0) from tableA

If data type for all 3 columns are integer or bigint you can you can have below query

select locks,keys,boxes,(locks,keys,boxes) as total_count from T1

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