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 |
CodePudding user response:
select a.id, a.data as [Name], b.data as [Gender], c.data as [Code]
from table1 a
left join table1 b on a.id = b.id and b.type='Gender'
left join table1 c on b.id = c.id and c.type='Code'
where a.type = 'Name'
CodePudding user response:
You can use CASE
expression instead of JOIN
s :
SELECT
a.id,
MAX(CASE WHEN a.data = 'Name' THEN a.data ELSE '' END) AS [Name],
MAX(CASE WHEN a.data = 'Gender' THEN a.data ELSE '' END) AS [Gender],
MAX(CASE WHEN a.data = 'Code' THEN a.data ELSE '' END) AS [Code]
FROM table1 a
WHERE
a.type IN('Name', 'Gender', 'Code')
GROUP BY a.id
CodePudding user response:
use a pivot query
select *
from table1
pivot
(
max(data)
for type in ([Name], [Gender], [Code])
) p