SQL Server Convert single rows to multiple rows

gwbalxhn  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(94)

I have an output which looks like
| Title A | Title B | Title C | Title D | Title E | Title F |
| ------------ | ------------ | ------------ | ------------ | ------------ | ------------ |
| Value 1 | Value 2 | Value 3 | Value 4 | Value 5 | Value 6 |

I need the output to be in this format:

Column AColumn B
Title AValue 1
Title BValue 2
Title CValue 3
Title DValue 4
Title EValue 5
Title FValue 6
gpfsuwkq

gpfsuwkq1#

I reckon you should change your original query to something along these lines:

SELECT condition AS ColumnA, COALESCE(SUM(Total), 0) AS ColumnB
FROM yourTable
WHERE condition IN ('A', 'B', ...)
GROUP BY condition;
tyu7yeag

tyu7yeag2#

Below Query will help you:

Drop table if exists #TempYourTable
CREATE table #TempYourTable (COLUMN_NAME nvarchar(500), COLUMN_VALUE nvarchar(max))

insert into #TempYourTable (COLUMN_NAME) 
select COLUMN_NAME 
from
(
    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'yourTable'
) as tbl_col_nm

Declare @Query nvarchar(max);
SELECT 
    @Query = ISNULL(@Query +';', '') + ISNULL('update #TempYourTable set COLUMN_VALUE = (select top 1 '+ isnull(T.COLUMN_NAME,'')+' from yourTable) where COLUMN_NAME = '''+T.COLUMN_NAME+'''', '')
FROM 
( 
    select COLUMN_NAME as COLUMN_NAME    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = N'yourTable'
)T

print @Query
Exec(@Query) 

select * from #TempYourTable
sh7euo9m

sh7euo9m3#

This is just a simple unpivot:

select col, value
from (
    VALUES  (N'Value 1', N'Value 2', N'Value 3', N'Value 4', N'Value 5', N'Value 6')
) t ([Title A],[Title B],[Title C],[Title D],[Title E],[Title F])
unpivot (value for col in ([Title A],[Title B],[Title C],[Title D],[Title E],[Title F])) upv

If you want dynamic one, there are plenty of answers available

相关问题