从SQL Server中的列透视和连接值

时间:2015-11-27 10:50:01

标签: sql-server pivot

我有这些列的表格:

ID | Name  | Value
------------------
 1 | Test1 | 0
 2 | Test2 | 1
 3 | Test3 | 0
 4 | Test4 | 0
 5 | Test5 | 1

我希望将值列转换并连接为字符串

01001

3 个答案:

答案 0 :(得分:2)

以下代码将给出预期结果:

SELECT @Result = @Result + CAST(VALUE AS VARCHAR)
FROM #TmpTestingTable

或者您可以使用STUFF

SELECT STUFF(
    (   SELECT CAST(VALUE AS VARCHAR) 
        FROM #TmpTestingTable
        FOR XML PATH ('')
    ), 1, 0, '')

对于示例,我将列插入临时表并执行代码。

CREATE TABLE #TmpTestingTable (ID INT, Name VARCHAR (20), Value INT)

INSERT INTO #TmpTestingTable (ID, Name, Value) VALUES
(1 , 'Test1' , 0),
(2 , 'Test2' , 1),
(3 , 'Test3' , 0),
(4 , 'Test4' , 0),
(5 , 'Test5' , 1)

DECLARE @Result AS VARCHAR (100) = '';

-- using variable approach
SELECT @Result = @Result + CAST(VALUE AS VARCHAR)
FROM #TmpTestingTable

SELECT @Result

-- using STUFF approach
SELECT STUFF(
    (   SELECT CAST(VALUE AS VARCHAR) 
        FROM #TmpTestingTable
        FOR XML PATH ('')
    ), 1, 0, '')

DROP TABLE #TmpTestingTable

答案 1 :(得分:2)

使用FOR XML进行连接。重要的是,您还要包含ORDER BY。否则,您无法控制值的顺序,并且存在任意顺序的风险。

@Rule
public PowerMockRule rule = new PowerMockRule();

答案 2 :(得分:0)

SELECT GROUP_CONCAT(Value SEPARATOR '') FROM Table

修改

不在SQL Server上工作。看看Simulating group_concat MySQL function in Microsoft SQL Server 2005?,试着让它发挥作用