SQL, how to find a nonzero column?

I have a table with a lot of columns, let's say I have columns

A, B, C, D

in each of these columns only one column will be filled in any one record, and the rest will always be NULL.

I need a select statement that will return a column of a nonzero column.

I tried to combine, but this returns the value, not the column to which the value belongs.

Does anyone know the easiest way to do this?

+5
source share
5 answers
SELECT
    CASE
        WHEN A IS NOT NULL THEN 'A'
        WHEN B IS NOT NULL THEN 'B'
        WHEN C IS NOT NULL THEN 'C'
        WHEN D IS NOT NULL THEN 'D'
    END
FROM
    MyTable
+8
source

Try the case ...

SELECT
CASE WHEN A IS NOT NULL THEN 'A' WHEN B IS NOT NULL THEN 'B' WHEN C IS NOT NULL THEN 'C' WHEN D IS NOT NULL THEN 'D' END as NotNullCol, OtherCols
FROM YourTable
+4
source

, - , , , .

A, B, C D , JOIN.

, NULL, , (A, B, C D) . , ( , ).

case:

select case
    when A is not null then 'A'
    when B is not null then 'B'
    when C is not null then 'C'
    else                    'D'
    end
from ...

, . , , ( ).

+3

, , :

select case 
    when a is not null then 'a' 
    when b is not null then 'b' 
    when c is not null then 'c' 
    when d is not null then 'd' 
end
+2

. alawys , .

. , , , , .

. , , . , , -, , , , , .

0

All Articles