kee
kee

Reputation: 11629

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).

Upvotes: 1

Views: 49

Answers (2)

sardar
sardar

Reputation: 145

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

Upvotes: 0

Ed Bangga
Ed Bangga

Reputation: 13006

you can use coalesce() function then add your columns

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

Upvotes: 3

Related Questions