如何将一列中的值连接起来?

时间:2019-02-07 16:43:59

标签: sql sql-server

我有一个具有两列关系类型的表,并且与 像以下内容一样,我希望所有具有“ T”的关系类型值都存在于一列中

+------------+---------+
|relationship|liveswith|
+------------+---------+
|A           |T        |
+------------+---------+
|B           |T        |
+------------+---------+
|C           |F        |
+------------+---------+

喜欢

+------------+---------+
|T           |F        |
+------------+---------+
|A B         |C        |
+------------+---------+

我尝试使用Pivot,但在T列中仅给我一个值。我正在使用Microsoft SQL Server 2012

2 个答案:

答案 0 :(得分:1)

您可以使用xml path('')并按以下方式使用STUFF

 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 |
+-----+---+

答案 1 :(得分:1)

您可以使用case语句确定对错:

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;

输出:

  t   |  f
------+-----
 A B  |   C