Search code examples
sql-serversql-server-2014-express

Displaying 2 different length columns from SQL query when pulling from 1 table


I use the following code to pull data from my table.

    SELECT 
    CASE WHEN VendorContactLName LIKE '%[s]'
        THEN VendorContactFName + ' ' + VendorContactLName + '''' END AS 'Test',
    CASE WHEN VendorContactLName NOT LIKE '%[s]'
        THEN VendorContactFName + ' ' + VendorContactLName + '''s' END AS 'Test2'
    FROM Vendors;

Currently, this returns 2 columns as it should, but where the first condition isn't true, it places "NULL" in the Test Column and where the second condition isn't true, it returns NULL in its respective column. I'd like it to not do this, and instead incrementally add rows based on whether or not the condition is met and avoid the rows with NULL in them.

EDIT: Not sure how it wasn't clear, but for a visual representation this is what DOES happen with the current code.

Test            Test2
NULL            Francesco Alberto's
NULL            Ania Irvin's
NULL            Lukas Liana's
NULL            Kenzie Quinn's
Michelle Marks' NULL
NULL            Anton Mauro's
NULL            Ted Maegen's
NULL            Erick Kaleigh's
NULL            Kaitlyn Anthoni's
NULL            Bill Leigh's
NULL            Kaitlin Hostlery's

What I want is this:

    Test            Test2
Michelle Marks'    Francesco Alberto's
                   Ania Irvin's
                   Lukas Liana's
                   Kenzie Quinn's
                   Anton Mauro's
                   Ted Maegen's
                   Erick Kaleigh's
                   Kaitlyn Anthoni's
                   Bill Leigh's
                   Kaitlin Hostlery's

Solution

  • In that case use a outer query to filter out NULL like below. Here XXX is the table alias for the inline query resultset.

    SELECT * FROM (
        SELECT 
    CASE WHEN VendorContactLName LIKE '%[s]'
        THEN VendorContactFName + ' ' + VendorContactLName + '''' END AS 'Test',
    CASE WHEN VendorContactLName NOT LIKE '%[s]'
        THEN VendorContactFName + ' ' + VendorContactLName + '''s' END AS 'Test2'
        FROM Vendors ) XXX
    WHERE Test IS NOT NULL AND Test2 IS NOT NULL;
    

    (OR)

    Using ISNULL() function like

    SELECT ISNULL(Test, '') as Test, ISNULL(Test2,'') as Test2 FROM (
        SELECT 
    CASE WHEN VendorContactLName LIKE '%[s]'
        THEN VendorContactFName + ' ' + VendorContactLName + '''' END AS 'Test',
    CASE WHEN VendorContactLName NOT LIKE '%[s]'
        THEN VendorContactFName + ' ' + VendorContactLName + '''s' END AS 'Test2'
        FROM Vendors ) XXX