Home > front end >  SQL query (at least)
SQL query (at least)

Time:12-14

I'm trying to write an SQL query but I couldn't translate the idea into code, and I'm seeking help here.

So, what I want to perform is: If one of these columns have value then 1 else 0, I mean, at least if one of these 4 columns have value then count.

I hope I'm clear enough, thank you in advance :)

CodePudding user response:

for columns c1, c2, c3, c3 try IF ( CONDITION, 0, 1) where CONDITION is (A and B and C and D) where A is ( ISNULL ( c1 )) or combined

 IF ( (ISNULL(c1) and ISNULL(c2) and ISNULL(c3) and ISNULL(c4)) , 0, 1)

CodePudding user response:

Using conditional COUNT_IF and COALESCE():

SELECT COUNT_IF(COALESCE(col1, col2, col3, col4) IS NOT NULL) AS cnt
FROM tab;

If any column contains data then COALESCE will pick the first value, satisfy the IS NOT NULL condition and count it.

  • Related