如何在sql中将2行变成单行

时间:2011-03-03 05:57:12

标签: sql sql-server-2005

  I have a query

   example

           Title  Description
             A      XYZ
             A      ABC

   now i want a sql query so that i can get a single row

  Output :

         Title  Description
          A      XYZ | ABC

5 个答案:

答案 0 :(得分:1)

Declare @tbl table(Title nvarchar(1),[Description] nvarchar(100))
Insert into @tbl values('A','XYZ'); 
Insert into @tbl values('A','ABC'); 
Insert into @tbl values('A','PQR'); 
DECLARE @CSVList varchar(100)

SELECT @CSVList = COALESCE(@CSVList + ' | ', '') + 
   [Description]
FROM @tbl
WHERE Title='A'

SELECT @CSVList

答案 1 :(得分:1)

declare @table table (i int, a varchar(10))
insert into @table
    select 1, 'ABC' union all
    select 1, 'XYZ' union all
    select 2, '123'

select  t.i, 
        max(stuff(d.i, 1, 1, '')) [iList]
from    @table t
cross 
apply   (   select  '|' + a
            from    @table [tt]
            where   t.i = tt.i
            for xml path('')
        ) as d(i)
group
by      t.i;

答案 2 :(得分:0)

在mysql中有一个group_concat函数,可以帮到你。 像这样使用它:

SELECT Title,GROUP_CONCAT(Description) FROM table_name GROUP BY Title

输出

 Title  Description
   A      XYZ,ABC

然后你可以用“|”替换“,”如果你想(可以用替换功能完成)

答案 3 :(得分:0)

对于2行,您可以在SQL Server中自行加入。这避免了各种“将行连接成列”的技巧。您也可以使用LEFT JOIN和NULL处理1行或2行

SELECT
   T1.Title,
   T1.Description + '|' + T2.Description
FROM
  MyTable T1
  JOIN
  MyTable T2 ON T1.Title = T2.Title

SELECT
   T1.Title,
   T1.Description + ISNULL('|' + T2.Description, '') --COALESCE for the pedants)
FROM
  MyTable T1
  LEFT JOIN
  MyTable T2 ON T1.Title = T2.Title

答案 4 :(得分:0)

如果您使用的是SQL Server,请尝试以下操作:How to return 1 single row data from 2 different tables with dynamic contents in sql