从两列sql创建一行

时间:2018-08-13 11:13:30

标签: sql sql-server

如何从两列创建一行?

示例:

id    description
------------------
1      one
2      two
3      three

结果:

1: one, 2: two, 3: three

我使用以下声明:

select Id,
  stuff((SELECT distinct ', ' + cast(Description as varchar(10))
           FROM dbo.tbl t2
           where t2.Id = t1.Id
           FOR XML PATH('')),1,1,'') 
from dbo.tbl t1
group by Id

但是结果是我有两列。我需要一个诸如字符串

的字符串

4 个答案:

答案 0 :(得分:2)

您可以尝试此查询。

CREATE TABLE T (
   id int,
   description varchar(50)
);

INSERT INTO T  VALUES (1,'one');
INSERT INTO T  VALUES (2,'two');
INSERT INTO T  VALUES (3,'three');

查询1

select 
      stuff((SELECT ', ' + CAST(t2.ID AS VARCHAR(5)) + ':'+ t2.description 
               FROM t t2
               FOR XML PATH('')),1,1,'') 

Results

|                        |
|------------------------|
|  1:one, 2:two, 3:three |

答案 1 :(得分:2)

我想你是要这个

select stuff((SELECT ', ' + CAST(tbl.id AS varchar) + ':' + tbl.description
FROM tablename tbl FOR XML PATH('')), 1, 1, '')  as Columnname

答案 2 :(得分:1)

你靠近了。

declare   @T TABLE  (
  id int,
   description varchar(50)
);

INSERT INTO @T  VALUES (1,'one');
INSERT INTO @T  VALUES (2,'two');
INSERT INTO @T  VALUES (3,'three');

select Id,
  stuff((SELECT distinct ', ' + +cast(id as nvarchar) +':'+description
           FROM @T t2
           where t2.Id = t1.Id
           FOR XML PATH('')),1,1,'') 
from @T t1
group by Id

或者如果您想在单行中使用所有ID,请使用以下查询

select stuff((select ',' +cast(id as nvarchar) +':'+description  
from @T for xml path('')),1,1,'')

答案 3 :(得分:0)

select语句就像一个for循环或迭代器,您需要一个空间来保存数据,而select只能使用它,因为此时select语句只能访问一行而不是前一行而不是下一行,所以< / p>

请使用缩放比例值函数

create function test()
return
    nvarchar(max)
as
begin

    declare @s nvarchar(max)

    select @s = concate(@s, id, description)
    from yourTable

    return @s
end