RobertKing
RobertKing

Reputation: 1911

SQL Query to get column result conditionally based on column value

Below is my SQL Table,

enter image description here

how do i get the result from this table as pack_cd and date which is not null. e.g.

enter image description here

from SQL Table i want to get PACK_CD and date as

Upvotes: 0

Views: 218

Answers (2)

Ajay2707
Ajay2707

Reputation: 5798

This is alternate option to understand. The same you achieve COALESCE as @wewesthemenace suggested.

SELECT
    PACK_CD,
    DATE = case when isnull(ETDT,'') != '' then ETDT 
                else 
                    case when isnull(PPDT,'') != '' then PPDT 
                    else
                        PDT
                    end
                end             
FROM [YourTable]

Upvotes: 0

Felix Pamittan
Felix Pamittan

Reputation: 31879

Use COALESCE:

SELECT
    PACK_CD,
    DATE = COALESCE(ETDT, PPDT, PDT)
FROM [YourTable]

If you want to show only those rows with NULL column, just add a WHERE clause:

WHERE
    ETDT IS NULL
    OR PPDT IS NULL
    OR PDT IS NULL

Upvotes: 4

Related Questions