I have a table with two columns relationship type and lives with like the following, I want all the relationship types values which has 'T' in lives with column in one column
+------------+---------+
|relationship|liveswith|
+------------+---------+
|A |T |
+------------+---------+
|B |T |
+------------+---------+
|C |F |
+------------+---------+
like this
+------------+---------+
|T |F |
+------------+---------+
|A B |C |
+------------+---------+
I tried using Pivot but it only gives me one values in T column. I am using Microsoft SQL Server 2012
You can make use of for xml path('') and use STUFF as follows
create table data(relationship varchar(10),liveswith varchar(10));
insert into data values('A','T');
insert into data values('B','T');
insert into data values('C','F');
with temp_output
as (
SELECT a.liveswith
,STUFF((SELECT '-' + relationship
FROM data a1
WHERE a1.liveswith=a.liveswith
ORDER BY relationship
FOR XML PATH('')), 1, 1, '') AS listStr
FROM data a
GROUP BY a.liveswith
)
select max(case when liveswith='T' then liststr end) as 'T'
,max(case when liveswith='F' then liststr end) as 'F'
from temp_output
+-----+---+
| T | F |
+-----+---+
| A-B | C |
+-----+---+
You can pivot on true/false with case statements:
SELECT
string_agg(CASE WHEN liveswith THEN relationship ELSE '' END, ' ') AS T,
string_agg(CASE WHEN NOT liveswith THEN relationship ELSE '' END, ' ') AS F
FROM foobar;
Output:
t | f
------+-----
A B | C
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.