简体   繁体   English

如何将单列拆分为多列

[英]How to split single column into multiple columns

I have a SQL Server table table_name like: 我有一个SQL Server表table_name像:

col1            col2
SomeString_1    23
SomeString_1    65
SomeString_1    300
SomeString_1    323

What I want to do is for one unique value in col1, I want to select all the values from col2 but each in it's own column. 我想对col1中的一个唯一值进行操作,我想从col2中选择所有值,但每个值都在其自己的列中。

So the query should be something like: 因此查询应类似于:

select col2 from table_name where col1 = 'SomeString_1';

But I need output in the form: 但是我需要以下形式的输出:

23  65  300 323

Basically each selected value should be in it's own column. 基本上,每个选定的值都应在其自己的列中。 So the result should always have one row and as many columns as the SomeString_1 is repeated. 因此,结果应该始终具有一行,重复的SomeString_1列数一样多。

I tried to search on SO but few questions I found had different conditions. 我尝试搜索SO,但是发现的几个问题有不同的条件。

An approach can be applied by using FOR XML : 可以通过使用FOR XML来应用一种方法:

SELECT DISTINCT t.COL1, 
        (SELECT t1.COL2 + ' ' AS 'data()'
         FROM @TBL t1 
         WHERE t.COL1 = t1.COL1
         FOR XML PATH(''))
FROM @TBL t
WHERE t.COL1 = 'SomeString_1'

An example, 一个例子,

DECLARE @TBL TABLE (COL1 VARCHAR(100), COL2 VARCHAR(10))
INSERT INTO @TBL VALUES ('SomeString_1', '23'), 
                        ('SomeString_1', '65'), 
                        ('SomeString_1', '300'),
                        ('SomeString_1', '323')

SELECT DISTINCT t.COL1, 
        (SELECT t1.COL2 + ' ' AS 'data()'
         FROM @TBL t1 
         WHERE t.COL1 = t1.COL1
         FOR XML PATH(''))
FROM @TBL t
WHERE t.COL1 = 'SomeString_1'

which returns, 返回,

COL1            (No column name)
SomeString_1    23  65  300  323 

Seems like OP is asking for separate column value for each row value: 好像OP正在为每个行值要求单独的列值:

create table #Table1 (COL1 VARCHAR(100), COL2 VARCHAR(10))
INSERT INTO #Table1 VALUES ('SomeString_1', '23'), 
                          ('SomeString_1', '65'), 
                          ('SomeString_1', '300'),
                          ('SomeString_1', '323')

DECLARE @columns nvarchar(MAX) = STUFF((
SELECT DISTINCT ',[col-' + cast(row_number() over (order by (select 1)) as varchar(4))+']'
FROM #Table1
FOR XML PATH('')), 1, 1, '')

DECLARE @sql nvarchar(MAX) = N'
SELECT * FROM
(
    SELECT col2, ''col-'' + cast(row_number() over (order by (select 1)) as varchar(4)) as dupcol2
    FROM #Table1 where col1 = ''SomeString_1''
) T
PIVOT
(MAX(col2) FOR dupcol2 IN ('+@columns+')) P'

EXEC (@sql)

Output: 输出:

col-1 | col-2 | col-3 | col-4
------------------------------
23    | 65    | 300   | 323

You can use COALESCE also.. 您也可以使用COALESCE。

DECLARE @Names VARCHAR(8000) 

SELECT @Names = COALESCE(@Names + ' ', '') + COL2
FROM YourTable
WHERE COL1 = 'SomeString_1'

SELECT @Names

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

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