Need to Pivot String values in SQL server - sql

I have table with values, described as:
Occupation String
Name String
Developer
A
Developer
B
Designer
X
Coder
Y
Coder
Z
I need values in pivot format as:
Designer
Developer
Coder
X
A
Y
Null
B
Z
Can anyone help on this ?
Thanks in advance

The basic PIVOT with ROW_NUMBER() will do things for you:
SELECT [Developer],
[Designer],
[Coder]
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY (SELECT NULL)) RN
FROM #temp
) as t
PIVOT (
MAX(Name) FOR Occupation IN ([Developer],[Designer],[Coder])
) as pvt
Output:
Developer Designer Coder
A X Y
B NULL Z
If the number of Occupations may vary then you need dynamic SQL:
DECLARE #columns nvarchar(max),
#sql nvarchar(max)
SELECT #columns = (
SELECT DISTINCT ','+QUOTENAME(Occupation)
FROM #temp
FOR XML PATH('')
)
SELECT #sql = N'
SELECT '+STUFF(#columns,1,1,'')+'
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY (SELECT NULL)) RN
FROM #temp
) as t
PIVOT (
MAX(Name) FOR Occupation IN ('+STUFF(#columns,1,1,'')+')
) as pvt'
EXEC sp_executesql #sql
Note: I have used ORDER BY (SELECT NULL) just to get some random ordering. Better use some actual field for this purpose.

Related

SQL Server - Dynamic Pivot with 2 Group Variables and 2 Aggregate Calculations

I have a dataset that is shaped like this:
I am trying to convert the data to this format:
As you can see, I'd like to sum the accounts and revenue (for each month) by State and Account Type. It is important to note that I seek a dynamic solution as these ARE NOT the only values (hard-coding is not an option!).
What SQL query can I write to accomplish this task, dynamically? (as these values are not the only ones present in the complete dataset).
Thanks!
I'm assuming you want to keep the columns in order by date, thus the top 100 percent ... order by in the section where we generate the columns
Example
Declare #SQL varchar(max) = '
Select *
From (
Select [State]
,[AccountType]
,B.*
From YourTable A
Cross Apply ( values (concat(''Accounts_'',format([Date],''MM/dd/yyyy'')),Accounts)
,(concat(''Revenue_'' ,format([Date],''MM/dd/yyyy'')),Revenue)
) B (Item,Value)
) A
Pivot (sum([Value]) For [Item] in (' + Stuff((Select ','+QuoteName('Accounts_'+format([Date],'MM/dd/yyyy'))
+','+QuoteName('Revenue_' +format([Date],'MM/dd/yyyy'))
From (Select top 100 percent [Date] from YourTable Group By [Date] Order by [Date] ) A
For XML Path('')),1,1,'') + ') ) p'
--Print #SQL
Exec(#SQL)
Returns
If it helps, the generated SQL looks like this:
Select *
From (
Select [State]
,[AccountType]
,B.*
From YourTable A
Cross Apply ( values (concat('Accounts_',format([Date],'MM/dd/yyyy')),Accounts)
,(concat('Revenue_' ,format([Date],'MM/dd/yyyy')),Revenue)
) B (Item,Value)
) A
Pivot (sum([Value]) For [Item] in ([Accounts_12/31/2017],[Revenue_12/31/2017],[Accounts_01/31/2018],[Revenue_01/31/2018]) ) p

SQL to Make XML Path list Columns

I have the following SQL Server query which cranks out a comma delimited list into one field.
Result looks like this 2003, 9083, 4567, 3214
Question: What would be the best way (SQL syntax) to put this into columns?
Meaning, I need these to show up as 1 column for "2003", 1 column for "9083" 1 column, for "4567" ..etc.
Obviously the number of columns would be dynamic based on the policy ID I give it . Any idea would be most appreciated.
My query is below .
SELECT DISTINCT x.ClassCode + ', '
FROM PremByClass x
WHERE x.PolicyId = 1673885
FOR XML PATH('')
If you take out the XML and the comma you are left with
SELECT DISTINCT x.ClassCode
FROM PremByClass x
WHERE x.PolicyId = 1673885
Which gives you a single column of the values, to turn this into columns you need to PIVOT it. However, you need to specify the names of the columns.
There is some more information in this answer https://stackoverflow.com/a/15931734/350188
You need PIVOT and if number of values could be different - dynamic SQL:
SELECT *
FROM (
SELECT DISTINCT ClassCode,
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) RN
FROM PremByClass
WHERE PolicyId = 1673885
) as t
PIVOT (
MAX(ClassCode) FOR RN IN ([1],[2],[3],[4])
) as pvt
Will give you:
1 2 3 4
-----------------------------
2003 9083 4567 3214
Dynamic SQL will be something like:
DECLARE #sql nvarchar(max),
#columns nvarchar(max)
SELECT #columns = STUFF((
SELECT DISTINCT ','+QUOTENAME(ROW_NUMBER() OVER (ORDER BY (SELECT NULL)))
FROM PremByClass
WHERE PolicyId = 1673885
FOR XML PATH('')
),1,1,'')
SELECT #sql = N'
SELECT *
FROM (
SELECT DISTINCT ClassCode,
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) RN
FROM PremByClass
WHERE PolicyId = 1673885
) as t
PIVOT (
MAX(ClassCode) FOR RN IN ('+#columns+')
) as pvt'
EXEC sp_executesql #sql
Assuming that there's a limit to the amount of numbers in that csv string.
You could cast or convert it to an xml type, and then put the values in as many columns you expect.
In this example it's assumed that there's no more than 6 values in the text:
declare #PolicyId INT = 1673885;
select PolicyId
,x.value('/x[1]','int') as n1
,x.value('/x[2]','int') as n2
,x.value('/x[3]','int') as n3
,x.value('/x[4]','int') as n4
,x.value('/x[5]','int') as n5
,x.value('/x[6]','int') as n6
from (
select
PolicyId,
cast('<x>'+replace(ClassCode,',','</x><x>')+'</x>' as xml) as x
from PremByClass
where PolicyId = #PolicyId
) q;

Adding a WHERE statement refering another table in Dynamic SQL

I currently have the following script which is pivoting results from rows into columns. It works a Great, apart from two issues;
I have a flag in another table which I want to filter by (basically: WHERE Table.Stats=YES). I'd normally do this in a basic query with an inner join followed by that WHERE statement. In the query below, I already have a WHERE FileSeq=25, which works, but this criteria I need to get working is calling on a different table.
The query is returning a lot of uncessary NULL fields.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT ',' + QUOTENAME(col+CAST(rn AS varchar(6)))
FROM
(
SELECT row_number() over(partition by UID ORDER BY ClassCode) rn
FROM dbo.StudentClasses
) d
CROSS APPLY
(
SELECT 'ClassCode', 1
) c (col, so)
GROUP BY col, rn, so
ORDER BY rn, so
FOR XML PATH(''), TYPE
).VALUE('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT UID,' + #cols + '
FROM
(
SELECT UID, col+CAST(rn AS varchar(10)) col, VALUE
FROM
(
SELECT UID, classcode,
row_number() over(partition by UID ORDER BY classcode) rn
FROM StudentClasses WHERE FileSeq=25
) t
CROSS APPLY
(
SELECT ''classcode'', CAST(classcode AS varchar(6))
) c (col, VALUE)
) x
PIVOT
(
MAX(VALUE)
for col in (' + #cols + ')
) p '
EXECUTE(#query)
Any assistance appreciated

T-SQL Group Rows Into Columns

How can I group an (unknown) number of rows into a single row where the set columns determine the grouping?
For example, shift
Ref Name Link
==============================
1 John L1
1 John L2
1 John L8
2 Steve L1
2 Steve L234
Into
Ref Name ... ... ...
==========================================
1 John L1 L2 L8
2 Steve L1 L234 NULL
Thanks for any help
You might pivot the table using row_number() as a source of column names:
select *
from
(
select ref,
name,
link,
row_number() over (partition by ref, name order by link) rn
from table1
) s
pivot (min (link) for rn in ([1], [2], [3], [4])) pvt
Simply extend the list of numbers if you have more rows.
Live test is # Sql Fiddle.
If the number of different Links is unkown this needs to be done dynamically. I think this will work as required:
DECLARE #SQL NVARCHAR(MAX) = ''
SELECT #SQL = #SQL + ',' + QUOTENAME(Rownumber)
FROM ( SELECT DISTINCT ROW_NUMBER() OVER(PARTITION BY Ref, Name ORDER BY Link) [RowNumber]
FROM yourTable
) d
SET #SQL = 'SELECT *
FROM ( SELECT Ref,
name,
Link,
ROW_NUMBER() OVER(PARTITION BY Ref, Name ORDER BY Link) [RowNumber]
FROM yourTable
) data
PIVOT
( MAX(Link)
FOR RowNumber IN (' + STUFF(#SQL, 1, 1, '') + ')
) pvt'
EXECUTE SP_EXECUTESQL #SQL
It is a slight varation of the usual PIVOT function because normally link would be in the column header. It basically determines the number of columns required (i.e. the maximum distinct values for Link per ref/Name) then Pivots the values into these columns.

get cross tabulated report according to data available - pivot

I want to pivot and turn an existing table and generate a report(cross tabulated). You see vals column is determined by unique combination of date_a and date_e columns. I don't know how to do this.
Something like this:
Test data
CREATE TABLE #tbl(date_a DATE,date_e DATE, vals FLOAT)
INSERT INTO #tbl
VALUES
('2/29/2012','1/1/2013',28.47),
('2/29/2012','2/1/2013',27.42),
('2/29/2012','3/1/2013',24.36),
('3/1/2012','1/1/2013',28.5),
('3/1/2012','2/1/2013',27.35),
('3/1/2012','3/1/2013',24.39),
('3/6/2012','1/1/2013',27.75),
('3/6/2012','2/1/2013',26.63),
('3/6/2012','3/1/2013',23.66)
Query
SELECT
*
FROM
(
SELECT
tbl.date_a,
tbl.date_e,
vals
FROM
#tbl AS tbl
) AS SourceTable
PIVOT
(
SUM(vals)
FOR date_e IN ([1/1/2013],[2/1/2013],[3/1/2013])
) AS pvt
DROP TABLE #tbl
EDIT
If you do not know how many columns there is then you need to do a dynamic pivot. Like this:
The unique columns
DECLARE #cols VARCHAR(MAX)
;WITH CTE
AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY date_e ORDER BY date_e) AS RowNbr,
tbl.*
FROM
#tbl AS tbl
)
SELECT #cols=STUFF
(
(
SELECT
',' +QUOTENAME(date_e)
FROM
CTE
WHERE
CTE.RowNbr=1
FOR XML PATH('')
)
,1,1,'')
Dynamic pivot
DECLARE #query NVARCHAR(4000)=
N'SELECT
*
FROM
(
SELECT
tbl.date_a,
tbl.date_e,
vals
FROM
#tbl AS tbl
) AS SourceTable
PIVOT
(
SUM(vals)
FOR date_e IN ('+#cols+')
) AS pvt'
EXECUTE(#query)