使用SQL时将多行合并为一行(一列)

时间:2015-02-10 03:22:07

标签: sql sql-server return

如何将多行合并为一行:

Example:
ID   NAME    NUMBER
24   infill  20
25   test1   10
26   test2   30
27   test5   35
28   test3   40

SELECT 
      name,
      number 
FROM table1 WHERE table1.id IN (24,26,28)

他们的结果如下:

NAME    NUMBER
infill  20
test2   30
test3   40

如何修改上面的SQL语句:我有一个我真正想要的列名。

服务

infill 20,test2 30, test3 40

我做了:

select name + " " + number as Service 
from table1
where table1.id in (24,26,28)

结果是NULL,谢谢大家回复我的问题。

3 个答案:

答案 0 :(得分:1)

你很接近,因为你试图用Int来连接varchar,所以concat没有工作的原因。

为了连接,两列必须具有相同的数据类型,请尝试这样:

SELECT name + ' ' + Convert(nvarchar(max), number) AS Service 
FROM table1
WHERE table1.id IN (24,26,28)

答案 1 :(得分:0)

这是

DECLARE @Str Varchar(max) = ''
SELECT @Str = @Str + Name + ' ' + CAST(Number As varchar) + ', ' AS Service FROM table1
WHERE table1.id in (24,26,28)
SELECT SUBSTRING(@Str, 0, LEN(@Str) - 2) AS Result

<强>更新

更简单

DECLARE @Str Varchar(max) 
SELECT @Str = COALESCE(@Str + ', ','') + Name + ' ' + CAST(Number As varchar) AS Service
FROM table1
WHERE table1.id in (24,26,28)
SELECT @Str AS Result

答案 2 :(得分:0)

试试这个

  DECLARE @MyTable TABLE
  (
     ID     INT,
     NAME   VARCHAR(100),
     NUMBER INT
  )

INSERT INTO @MyTable
VALUES      (24,
             'infill',
             '20'),
            (25,
             'test1',
             '10'),
            (26,
             'test2',
             '30'),
            (27,
             'test5',
             '35'),
            (28,
             'test3',
             '40')

SELECT stuff((SELECT ',' + NAME + ' ' + CONVERT(VARCHAR(100), NUMBER)
              FROM   @MyTable
              WHERE  id IN ( 24, 26, 28 )
              FOR XML PATH('')), 1, 1, '') AS SERVICE