Search code examples
sqlsql-serversql-server-2008database-table

Display empty value when there is no data on the table


I have table and query to select data from row to column like this:

 id  |  type    | data
-----------------------
  1  |  Name    | John
  1  |  Gender  | Male
  1  |  Code    | 1782
  2  |  Name    | Dave
  2  |  Gender  | Male

Query:

select a.id, a.data as [Name], b.data as [Gender], c.data as [Code]
from table1 a join table1 b on a.id = b.id
              join table1 c on b.id = c.id
where a.type = 'Name' and b.type = 'Gender' and c.type = 'Code'

Result:

  id |  Name   | Gender | Code  
 ------------------------------
  1  |  John   |  Male  | 1782

In this case id number 2 with the name 'Dave' doesn't have a 'Code' so it wont appear in the result. How can I still display the result with empty data or NULL on the 'Code' table so it will have result like this:

  id |  Name   | Gender | Code  
 ------------------------------
  1  |  John   |  Male  | 1782 
  2  |  Dave   |  Male  |

Solution

  • You can use CASE expression instead of JOINs :

    SELECT
      a.id,
      MAX(CASE WHEN a.type = 'Name' THEN a.data ELSE '' END) AS [Name],
      MAX(CASE WHEN a.type = 'Gender' THEN a.data ELSE '' END) AS [Gender],
      MAX(CASE WHEN a.type = 'Code' THEN a.data ELSE '' END) AS [Code]
    FROM table1 a
    WHERE
        a.type IN('Name', 'Gender', 'Code')
    GROUP BY a.id