简体   繁体   English

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

[英]Combine Multiple Rows into One Row (One Column) when Using SQL

How to combine multiple rows into one row: 如何将多行合并为一行:

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)

They will have result as: 他们将得到如下结果:

NAME    NUMBER
infill  20
test2   30
test3   40

How to modify SQL statement above: and I have one column name as I really want. 如何修改上面的SQL语句:我确实想要一个列名。

Service 服务

infill 20,test2 30, test3 40

I did: 我做了:

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

Result is NULL, thank you all for reply my question. 结果为NULL,谢谢大家回答我的问题。

You are close, the reason concat is not working since you aretrying to concat varchar with Int. 您接近了,因为您正尝试使用Int连接varchar,所以concat无法正常工作的原因。

In order to concat, both the columns have to be of same datatype, try like this: 为了合并,两列必须具有相同的数据类型,请尝试如下操作:

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

Here is it 就这个

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

UPDATE: 更新:

More Simple 更简单

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

Try like this 这样尝试

  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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM