Reputation: 1031
I have a SQL Server table table_name like:
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.
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.
I tried to search on SO but few questions I found had different conditions.
Upvotes: 1
Views: 1271
Reputation: 2156
Seems like OP is asking for separate column value for each row value:
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
Upvotes: 2
Reputation: 5031
You can use COALESCE also..
DECLARE @Names VARCHAR(8000)
SELECT @Names = COALESCE(@Names + ' ', '') + COL2
FROM YourTable
WHERE COL1 = 'SomeString_1'
SELECT @Names
Upvotes: 1
Reputation: 91766
An approach can be applied by using 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
Upvotes: 2