Related
I found this great post for transposing a table in sql:
Simple way to transpose columns and rows in Sql?
edit:
input:
Paul | John | Tim | Eric
Red 'hi' | 5 | 1 | 3.3
Green 'there' | 4 | 3 | 5.5
Blue 'everyone'| 2 | 9 | 7.5
expected output:
Red | Green | Blue
Paul 'hi' | 'there' | 'everyone'
John 5 | 4 | 2
Tim 1 | 3 | 9
Eric 3.3 | 5.5 | 7.5
And I wanted to employ the last dynamic solution for a table that has different data types dynamically:
CREATE TABLE yourTable([color] nvarchar(5), [Paul] nvarchar(10), [John] int, [Tim]
int, [Eric] float);
INSERT INTO yourTable
([color], [Paul], [John], [Tim], [Eric])
VALUES
('Red', 'hi', 5, 1, 3.3),
('Green', 'there', 4, 3, 5.5),
('Blue', 'everyone', 2, 9, 7.5);
When I run the code from the previous answer:
DECLARE #colsUnpivot AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX),
#colsPivot as NVARCHAR(MAX)
select #colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id('yourtable') and
C.name <> 'color'
for xml path('')), 1, 1, '')
select #colsPivot = STUFF((SELECT ','
+ quotename(color)
from yourtable t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query
= 'select name, '+#colsPivot+'
from
(
select color, name, value
from yourtable
unpivot
(
value for name in ('+#colsUnpivot+')
) unpiv
) src
pivot
(
sum(value)
for color in ('+#colsPivot+')
) piv'
exec(#query)
When I run this code I get the error message:
The type of column "John" conflicts with the type of other columns specified in the UNPIVOT list.
Is there a way that I can use this dynamic solution for my table without losing the dynamic nature of it? I'd like to ideally pass a bunch of tables into this method to transpose them in batch.
Thanks
A method to overcome this would be to use the data type SQL_VARIANT so that the resulting columns can handle more than a single data type. However you cannot SUM() SQL_VARIANT columns, so sum(value) has to be changed to max(value) - or min(value) - but for this pivot that change does not alter the result.
DECLARE #colsConvert AS NVARCHAR(MAX)
DECLARE #colsUnpivot AS NVARCHAR(MAX)
DECLARE #colsPivot as NVARCHAR(MAX)
DECLARE #query AS NVARCHAR(MAX)
select #colsConvert = (select ', cast('+quotename(C.name)+' as sql_variant) as '+quotename(C.name)
from sys.columns as C
where C.object_id = object_id('yourtable') and
C.name <> 'color'
for xml path(''))
select #colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id('yourtable') and
C.name <> 'color'
for xml path('')), 1, 1, '')
select #colsPivot = STUFF((SELECT ','
+ quotename(color)
from yourtable t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query
= 'select name, '+#colsPivot+'
from
(
select color, name, value
from (select color'+#colsConvert+' from yourtable) as converted
unpivot
(
value for name in ('+#colsUnpivot+')
) unpiv
) src
pivot
(
max(value)
for color in ('+#colsPivot+')
) piv'
exec(#query)
See this working at: http://rextester.com/IBSN39688
Result:
+------+-----+-------+----------+
| name | Red | Green | Blue |
+------+-----+-------+----------+
| Eric | 3.3 | 5.5 | 7.5 |
| John | 5 | 4 | 2 |
| Paul | hi | there | everyone |
| Tim | 1 | 3 | 9 |
+------+-----+-------+----------+
The generated SQL:
select name, [Red],[Green],[Blue]
from
(
select color, name, value
from (select color, cast([Eric] as sql_variant) as [Eric], cast([John] as sql_variant) as [John], cast([Paul] as sql_variant) as [Paul], cast([Tim] as sql_variant) as [Tim] from yourtable) as converted
unpivot
(
value for name in ([Eric],[John],[Paul],[Tim])
) unpiv
) src
pivot
(
max(value)
for color in ([Red],[Green],[Blue])
) piv
+EDIT
An added benefit of using SQL_VARIANT in the result columns is that each standard data type encountered will adopt its default format. Particularly relevant for decimal/float and date/time data. You could also amend the defaults before running the dynamic pivot to further influence the output.
Demonstrated here
The following will transpose virtually any table, view, or query while respecting Row and Column sequences.
Full Disclosure: There is one major drawback. This approach does NOT handle NULL values well. A NULL value will cause the following columns to shift to the left.
Example
Declare #YourTable Table ([Color] varchar(50),[Paul] varchar(50),[John] int,[Tim] int,[Eric] decimal(10,1))
Insert Into #YourTable Values
('Red','hi',5,1,3.3)
,('Green','there',4,3,5.5)
,('Blue','everyone',2,9,7.5)
Declare #XML xml = (Select *,RowNr=Row_Number() over (Order By (Select NULL)) From #YourTable for XML RAW)
Select RowNr = Row_Number() over(Partition By r.value('#RowNr','int') Order By (Select null))
,ColNr = r.value('#RowNr','int')
,Item = attr.value('local-name(.)','varchar(100)')
,Value = attr.value('.','varchar(max)')
Into #Temp
From #XML.nodes('/row') as XN(r)
Cross Apply XN.r.nodes('./#*') AS XA(attr)
Where attr.value('local-name(.)','varchar(100)') not in ('RowNr')
Declare #SQL varchar(max) = '
Select [Item],' + Stuff((Select Distinct ',' + QuoteName(ColNr)+' as '+QuoteName(Value) From #Temp Where RowNr=1 Order by 1 For XML Path('')),1,1,'') + '
From #Temp
Pivot (max([Value]) For [ColNr] in (' + Stuff((Select Distinct ',' + QuoteName(ColNr) From #Temp Order by 1 For XML Path('')),1,1,'') + ') ) p
Where RowNr>1
Order By RowNr'
Exec(#SQL);
Returns
Item Red Green Blue
Paul hi there everyone
John 5 4 2
Tim 1 3 9
Eric 3.3 5.5 7.5
dbFiddle
I want to convert rows into columns.
Column1 Column2 Column3 Column4 Column5 Column6 Column7
1 2016-07-25 7 3 c1 c11 c111
2 2016-07-26 5 2 c2 c22 c222
3 2016-07-27 1 2 c3 c33 c333
4 2016-07-28 3 1 c4 c44 c444
I want output as follows :
Column1 1 2 3 4
Column2 2016-07-25 2016-07-26 2016-07-27 2016-07-28
Column3 7 5 1 3
Column4 3 2 2 1
Column5 c1 c2 c3 c4
Column6 c11 c22 c33 c44
Column7 c111 c222 c333 c44
I tried to do it using pivot unpivot but did not find proper solution.
First Table (input) can have n number of rows.
You need to use UNPIVOT, then PIVOT and if columns number is unknown - dynamic SQL:
DECLARE #columns nvarchar(max),
#columns_with_convert nvarchar(max),
#row_numbers nvarchar(max),
#sql nvarchar(max)
SELECT #columns = STUFF((
SELECT ','+QUOTENAME(name)
FROM sys.columns
WHERE [object_id] = OBJECT_ID('##YourTable')
FOR XML PATH('')),1,1,'')
--Will get you [Column1],[Column2],[Column3],[Column4],[Column5],[Column6],[Column7]
SELECT #columns_with_convert = (
SELECT 'CAST('+QUOTENAME(name)+' as nvarchar(max)) as '+QUOTENAME(name) +','
FROM sys.columns
WHERE [object_id] = OBJECT_ID('##YourTable')
FOR XML PATH(''))
--Will get you CAST([Column1] as nvarchar(max)) as [Column1], ... because all rows must be same datatype.
SELECT #row_numbers = STUFF((
SELECT ','+ QUOTENAME(CAST(ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as nvarchar(max)))
FROM ##YourTable
FOR XML PATH('')),1,1,'')
--This will be used when PIVOTing ([1],[2],[3],[4])
SELECT #sql = '
SELECT *
FROM (
SELECT RN,
[Columns],
[Values]
FROM (
SELECT '+#columns_with_convert+'
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as RN
FROM ##YourTable
) as p
UNPIVOT (
[Values] FOR [Columns] IN ('+#columns+')
) as unpvt
) as s
PIVOT (
MAX([Values]) FOR RN IN ('+#row_numbers+')
) as pvt
'
EXEC sp_executesql #sql
Output:
Columns 1 2 3 4
Column1 1 2 3 4
Column2 2016-07-25 2016-07-26 2016-07-27 2016-07-28
Column3 7 5 1 3
Column4 3 2 2 1
Column5 c1 c2 c3 c4
Column6 c11 c22 c33 c44
Column7 c111 c222 c333 c444
If you PRINT #sql you will get a text of query:
SELECT *
FROM (
SELECT RN,
[Columns],
[Values]
FROM (
SELECT CAST([Column1] as nvarchar(max)) as [Column1],CAST([Column2] as nvarchar(max)) as [Column2],CAST([Column3] as nvarchar(max)) as [Column3],CAST([Column4] as nvarchar(max)) as [Column4],CAST([Column5] as nvarchar(max)) as [Column5],CAST([Column6] as nvarchar(max)) as [Column6],CAST([Column7] as nvarchar(max)) as [Column7],
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as RN
FROM ##YourTable
) as p
UNPIVOT (
[Values] FOR [Columns] IN ([Column1],[Column2],[Column3],[Column4],[Column5],[Column6],[Column7])
) as unpvt
) as s
PIVOT (
MAX([Values]) FOR RN IN ([1],[2],[3],[4])
) as pvt
I tried to do it using pivot unpivot but did not find proper solution.
First Table (input) can have n number of rows.
The reason why it didn't work is because PIVOT does not work for dynamic number of rows. Meaning the syntax can transpose only a fixed number of Rows as Columns and you need to specify that in the query. It cannot Dynamically auto generate columns on the fly based on the values in your rows.
Edit:
One Solution I found for dynamic pivot (1st result from google search) : https://www.mssqltips.com/sqlservertip/2783/script-to-create-dynamic-pivot-queries-in-sql-server/
It needs dynamic SQL (there is no other option)
DECLARE #TABLE TABLE
(RowNo INT,Col1 VARCHAR(10),Col2 VARCHAR(10)
,Col3 VARCHAR(10))
INSERT INTO #TABLE VALUES
(1,'A','B','C')
SELECT Kishore from #Table
Unpivot(Kishore For Value IN (Col1,Col2,Col3)) AS H
This question already has answers here:
SQL Server dynamic PIVOT query?
(9 answers)
Closed 8 years ago.
Looking for help with pivoting a result set as I'm very new to it.
Here I have test data inserted into a table.
CREATE TABLE #temp (procCode int, member_id varchar(10))
INSERT INTO #temp(procCode,member_id)
SELECT 90658,'jjjj'
UNION all
SELECT 90658,'k'
UNION all
SELECT 90658,'jjjkk'
UNION all
SELECT 90658,'jjjj'
UNION all
SELECT 90658,'k'
UNION all
SELECT 90658,'jjjkk'
UNION all
SELECT 90658,'jjjj'
UNION all
SELECT 90658,'k'
UNION all
SELECT 90649,'jjjj'
UNION all
SELECT 90649,'k'
UNION all
SELECT 906,'jjjj'
UNION all
SELECT 906,'jjjj'
select
member_id,procCode, COUNT(*) as countProcCode
FROM #temp
GROUP BY member_id,procCode
This right now outputs data like this:
member_id procCode CountProcCode
jjjj 906 2
jjjj 90649 1
jjjkk 90658 2
k 90649 1
jjjj 90658 3
k 90658 3
How I need it to display is like this:
member_id Count906 count90649 count90658
jjjj 2 1 3
k 0 1 3
jjjkk 0 0 2
Any help is greatly appreciated.
There are more than just these procCodes and member_id so I couldn't really say where member_id in (506,50658,50649) as there are additional ones that could appear.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.procCode)
FROM #temp c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT member_id, ' + #cols + ' from
(
select member_id, member_id as b
, procCode
from #temp
) x
pivot
(
count(b)
for procCode in (' + #cols + ')
) p '
execute(#query)
drop table #temp
Results
member_id 906 90649 90658
jjjj 2 1 3
jjjkk 0 0 2
k 0 1 3
Recomended reading
Hi I am trying in SQL Server the pivoting for the following table
REFID | COL1 | COL2 | Sequence
1 abc cde 1
1 lmn rst 2
1 kna asg 3
2 als zkd 2
2 zpk lad 1
I want the output as
REFID | 1COL1 | 2COL1 | 3COL1 |1COL2|2COL2|3COL2
1 abc lmn kna cde rst asg
2 zpk als null lad zkd null
The number of columns in the original table are known but the number of rows are not known. Can any one help
If you want to include the sequence number as part of your column names, then you will still need to unpivot your col1 and col2 columns first, then apply the pivot. The difference is that you will concatenate the sequence number to your column names created during the unpivot process.
For a known number of values the query would be:
select REFID,
[1col1], [2col1], [3col1],
[1col2], [2col2], [3col2]
from
(
select REFID,
col = cast(Sequence as varchar(10))+ col, value
from yourtable
cross apply
(
select 'COL1', col1 union all
select 'COL2', col2
) c (col, value)
) d
pivot
(
max(value)
for col in ([1col1], [2col1], [3col1],
[1col2], [2col2], [3col2])
) piv
order by refid;
Then if you have an unknown number the dynamic SQL version will be:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(cast(Sequence as varchar(10))+ col)
from yourtable
cross apply
(
select 'Col1', 1 union all
select 'Col2', 2
) c(col, so)
group by Sequence, col, so
order by so, sequence
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT refid, ' + #cols + '
from
(
select REFID,
col = cast(Sequence as varchar(10))+ col, value
from yourtable
cross apply
(
select ''COL1'', col1 union all
select ''COL2'', col2
) c (col, value)
) x
pivot
(
max(value)
for col in (' + #cols + ')
) p
order by refid'
execute sp_executesql #query;
I have read dozens of solutions to similar transposition problems as the one I am about to propose but oddly none that exactly mirrors my issue. I am simply trying to flip my rows to columns in a simple dashboard type data set.
The data when pulled from various transaction tables looks like this:
DatePeriod PeriodNumberOverall Transactions Customers Visits
'Jan 2012' 1 100 50 150
'Feb 2012' 2 200 100 300
'Mar 2012' 3 300 200 600
and I want to be able to generate the following:
Jan 2012 Feb 2012 Mar 2012
Transactions 100 200 300
Customers 50 100 200
Visits 150 300 600
The metrics will be static (Transactions, Customers and Visits), but the date periods will be dynamic (IE - more added as months go by).
Again, I have ready many examples leveraging pivot, unpivot, store procedures, UNION ALLs, etc, but nothing where I am not doing any aggregating, just literally transposing the whole output. I have also found an easy way to do this in Visual Studio 2005 using a matrix with an embedded list, but I can't export the final output to excel which is a requirement. Any help would be greatly appreciated.
In order to get the result that you want you need to first UNPIVOT the data and then PIVOT theDatePeriod` Values.
The UNPIVOT will transform the multiple columns of Transactions, Customers and Visits into multiple rows. The other answers are using a UNION ALL to unpivot but SQL Server 2005 was the first year the UNPIVOT function was supported.
The query to unpivot the data is:
select dateperiod,
col, value
from transactions
unpivot
(
value for col in (Transactions, Customers, Visits)
) u
See Demo. This transforms your current columns into multiple rows, so the data looks like the following:
| DATEPERIOD | COL | VALUE |
-------------------------------------
| Jan 2012 | Transactions | 100 |
| Jan 2012 | Customers | 50 |
| Jan 2012 | Visits | 150 |
| Feb 2012 | Transactions | 200 |
Now, since the data is in rows, you can apply the PIVOT function to the DatePeriod column:
select col, [Jan 2012], [Feb 2012], [Mar 2012]
from
(
select dateperiod,
t.col, value, c.SortOrder
from
(
select dateperiod,
col, value
from transactions
unpivot
(
value for col in (Transactions, Customers, Visits)
) u
) t
inner join
(
select 'Transactions' col, 1 SortOrder
union all
select 'Customers' col, 2 SortOrder
union all
select 'Visits' col, 3 SortOrder
) c
on t.col = c.col
) d
pivot
(
sum(value)
for dateperiod in ([Jan 2012], [Feb 2012], [Mar 2012])
) piv
order by SortOrder;
See SQL Fiddle with Demo.
If you have an unknown number of date period's then you will use dynamic SQL:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(dateperiod)
from transactions
group by dateperiod, PeriodNumberOverall
order by PeriodNumberOverall
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT col, ' + #cols + '
from
(
select dateperiod,
t.col, value, c.SortOrder
from
(
select dateperiod,
col, value
from transactions
unpivot
(
value for col in (Transactions, Customers, Visits)
) u
) t
inner join
(
select ''Transactions'' col, 1 SortOrder
union all
select ''Customers'' col, 2 SortOrder
union all
select ''Visits'' col, 3 SortOrder
) c
on t.col = c.col
) x
pivot
(
sum(value)
for dateperiod in (' + #cols + ')
) p
order by SortOrder'
execute(#query)
See SQL Fiddle with Demo. Both will give the result:
| COL | JAN 2012 | FEB 2012 | MAR 2012 |
-------------------------------------------------
| Transactions | 100 | 200 | 300 |
| Customers | 50 | 100 | 200 |
| Visits | 150 | 300 | 600 |
You need to dynamically create a SQL statement with PIVOT and APPLY operators on the fly and then run that command. If your metrics static(Transactions, Customers and Visits), hence we can use CROSS APPLY operator with VALUES As a Table Source.
For SQL Server2008+
DECLARE #cols nvarchar( max),
#query nvarchar(max)
SELECT #cols =
STUFF((SELECT ',' + QUOTENAME(t.DatePeriod) AS ColName
FROM dbo.test62 t
FOR XML PATH(''), TYPE).value ('.', 'nvarchar(max)'), 1, 1, '')
SET #query =
'SELECT *
FROM (
SELECT t.DatePeriod, COALESCE(o.Transactions, o.Customers, o.Visits) AS PvtVals, o.PvtColumns, o.OrderColumns
FROM dbo.test62 t CROSS APPLY (
VALUES(t.Transactions, NULL, NULL, ''Transaction'', 1),
(NULL, t.Customers, NULL, ''Customers'', 2),
(NULL, NULL, t.Visits, ''Visits'', 3)
) o (Transactions, Customers, Visits, PvtColumns, OrderColumns)
) p
PIVOT
(
MAX(PvtVals) FOR DatePeriod IN (' + #cols + ')
) AS pvt
ORDER BY pvt.OrderColumns '
EXEC(#query)
Result:
PvtColumns Jan 2012 Fed 2012 Mar 2012
Transaction 100 200 300
Customers 50 100 200
Visits 150 300 600
Demo on SQLFiddle
For SQL Server 2005
DECLARE #cols nvarchar( max),
#query nvarchar(max)
SELECT #cols =
STUFF((SELECT ',' + QUOTENAME(t.DatePeriod) AS ColName
FROM dbo.test62 t
FOR XML PATH(''), TYPE).value ('.', 'nvarchar(max)'), 1, 1, '')
SET #query =
'SELECT *
FROM (
SELECT t.DatePeriod, COALESCE(o.Transactions, o.Customers, o.Visits) AS PvtVals, o.PvtColumns, o.OrderColumns
FROM dbo.test62 t CROSS APPLY (
SELECT t.Transactions, NULL, NULL, ''Transaction'', 1
UNION ALL
SELECT NULL, t.Customers, NULL, ''Customers'', 2
UNION ALL
SELECT NULL, NULL, t.Visits, ''Visits'', 3
) o (Transactions, Customers, Visits, PvtColumns, OrderColumns)
) p
PIVOT
(
MAX(PvtVals) FOR DatePeriod IN (' + #cols + ')
) AS pvt
ORDER BY pvt.OrderColumns'
EXEC(#query)
If you can know how many different date period in advance, then you can use fixed query like following:
;with CTE_UNIONTable
as
(
select [DatePeriod],[PeriodNumberOverall],[Transactions] as [value], 'Transactions' as subType from table1
UNION ALL
select [DatePeriod],[PeriodNumberOverall],[Customers] as [value], 'Customers' as subType from table1
UNION ALL
select [DatePeriod],[PeriodNumberOverall],[Visits] as [value], 'Visits' as subType from table1
), CTE_MiddleResult
as
(
select * from CTE_UNIONTable
pivot
(
max(value)
for DatePeriod in ([Jan 2012],[Feb 2012],[Mar 2012])
) as P
)
select SubType, max([Jan 2012]) as [Jan 2012] ,max([Feb 2012]) as [Feb 2012], max([Mar 2012]) as [Feb 2012]
from CTE_MiddleResult
group by SubType
SQL FIDDLE DEMO
If how many date period is unpredictable, then #Alexander already gave the solution, the following code is just a second opinion, instead of using APPLY, using UNION ALL
DECLARE #cols nvarchar( max),
#query nvarchar (max),
#selective nvarchar(max)
SELECT #cols =
STUFF((SELECT ',' + QUOTENAME(t.DatePeriod) AS ColName
FROM table1 t
FOR XML PATH( ''), TYPE).value ('.', 'nvarchar(max)'),1,1,'')
SELECT #selective =
STUFF((SELECT ',MAX(' + QUOTENAME(t.DatePeriod) +') as ' + QUOTENAME(t.DatePeriod) AS ColName
FROM table1 t
FOR XML PATH( ''), TYPE).value ('.', 'nvarchar(max)'),1,1,'')
set #query = '
;with CTE_UNIONTable
as
(
select [DatePeriod],[PeriodNumberOverall],[Transactions] as [value], ''Transactions'' as subType from table1
UNION ALL
select [DatePeriod],[PeriodNumberOverall],[Customers] as [value], ''Customers'' as subType from table1
UNION ALL
select [DatePeriod],[PeriodNumberOverall],[Visits] as [value], ''Visits'' as subType from table1
), CTE_MiddleResult
as
(
select * from CTE_UNIONTable
pivot
(
max(value)
for DatePeriod in ('+#cols+')
) as P
)
select SubType,' + #selective + '
from CTE_MiddleResult
group by SubType'
exec(#query)
SQL FIDDLE DEMO