SQL Dynamic columns - sql

select #cols =
STUFF((SELECT ',' + QUOTENAME(grade)
from #temp
group by grade
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select #colsRollup = STUFF((SELECT ', Sum(' + QUOTENAME(grade) + ') as '+QUOTENAME (grade)
from #temp
group by grade
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query
= 'SELECT * into #temp3 from
(
SELECT lob as "Vertical", '+ #colsRollup + '
FROM
(
SELECT lob,' + #cols + ' from
(
select lob,
grade,
asso_count
from #temp
) x
pivot
(
count(grade)
for grade in (' + #cols + ')
) p
) x1
GROUP BY lob with ROLLUP)x2'
execute(#query)
I am trying to create dynamic columns and insert it into a temporary table.
But it throws an error saying that #temp3 is not a valid object name. the code works if i dont try to insert the dynamic generated columns into a table.

If you execute the code and then try to access the #temp3table like:
execute(#query)
select * from #temp3
I would think it will have gone out of scope, which would explain the error message.
You could try to modify your query to include a SELECTlike:
SET #query = '
SELECT * INTO #temp3 FROM
(
SELECT lob as "Vertical", '+ #colsRollup + '
FROM
(
SELECT lob,' + #cols + ' from (select lob, grade, asso_count from #temp) x
PIVOT (count(grade) for grade in (' + #cols + ')) p
) x1
GROUP BY lob with ROLLUP
) x2; SELECT * FROM #temp3'
Note how the last line now includes ; SELECT * FROM #temp3
If you add that you should get the results back, if that is what you want.

Related

Convert Columns values into Rows in SQL 2008

It would be great if you can help me to convert Column into Rows in SQL Table.
Let say, I have 3 columns called:
Employee_ID
Shift_Date
Shift_ID
Currently it come up like this:
Table Like this
I want to appear like that as the result -
Result Table
But I want value in it, can you guys please help. Thanks.
This is a query I wrote but still error:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(shift_date)
from dbo.tbl_Multi_Shift_Employee WHERE Shift_Date BETWEEN CONVERT(DATE, '01/02/2018 00:00:00',103) AND CONVERT(DATE, '28/02/2018 00:00:00',103)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Employee_ID, total, Department_ID, shift_id, ' + #cols + ' from
(
select count(*) over(partition by t.Employee_ID) total,
s.Department_ID,
t.Employee_ID,
t.shift_id
from dbo.tbl_Multi_Shift_Employee t
inner join dbo.tbl_department s
on t.Department_ID = s.Department_ID
) x
pivot
(
count(shift_id)
for shift_id in (' + #cols + ')
) p '
PRINT #query
execute(#query)
First you must to remove shift_id from primary select because is used as pivot.
Second, change shift_id with shift_date that is the correct column you are using as pivot columns.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(shift_date)
from dbo.tbl_Multi_Shift_Employee WHERE Shift_Date BETWEEN CONVERT(DATE, '01/02/2018 00:00:00',103) AND CONVERT(DATE, '28/02/2018 00:00:00',103)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Employee_ID, total, Department_ID, ' + #cols + ' from
(
select count(*) over(partition by t.Employee_ID) total,
s.Department_ID,
t.Employee_ID,
t.shift_id,
t.shift_date
from dbo.tbl_Multi_Shift_Employee t
inner join dbo.tbl_department s
on t.Department_ID = s.Department_ID
) x
pivot
(
count(shift_id)
for shift_date in (' + #cols + ')
) p '
PRINT #query
execute(#query)

Pivot for Unknown number of values in description- SQL Server 2008

May some one please help me how to get the result in SQL SERVER 2008
Are you trying to do something like this:
IF OBJECT_ID('tempdb..#TABLE') IS NOT NULL
BEGIN;
DROP TABLE #TABLE;
END;
CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)
INSERT #TABLE
SELECT 'RESISTOR', 'POWER' UNION ALL
SELECT 'RESISTOR', 'Type' UNION ALL
SELECT 'RESISTOR', 'DESIGN' UNION ALL
SELECT 'RESISTOR', 'Material' UNION ALL
SELECT 'OTHER', 'Other' UNION ALL
SELECT 'OTHER', 'Material';
DECLARE #cols NVARCHAR(MAX)
,#query NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(Description)
from #TABLE
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT [Generic Name], ' + #cols + '
FROM
(
SELECT [Generic Name], [Generic Name] AS [BaseName], [Description]
from #TABLE
) DS
pivot
(
COUNT([BaseName])
for [Description] in (' + #cols + ')
) p '
SELECT #query
execute(#query)
This will show you the count (but if you have only one record for each description it will be only true/have or false/not have) of each generic name.
Try the below change in your query
set #query = 'SELECT ' + #cols + ' from
(
select [Generic Name], Description
from #TABLE
) x
pivot
(
MAX([Generic Name])
for Description in (' + #cols + ')
) p '
Since you are pivoting the records, there won't be a column [Generic Name] -- I Don't see any such column in the table structure so I'm assuming that you need to column Base Name-- so, the #Cols parameter is enough
Please Check the Demo here

How To Set NULL is 0 in SQL Dynamic Pivot Query

I developed one dynamic pivot table, and I set ISNULL = 0.00.
The query is given below
SELECT DISTINCT hdr.EmpNo,hdr.FirstName AS Name,
ISNULL(TBL.shortname,'')AS shortname,
ISNULL(TBL.Amount,0.00) AS Amount,
TBL.Adtype INTO #Temp FROM tbl1 AS hdr
LEFT JOIN tbl2 TBL ON TBL.EmpNo = hdr.EmpNo
DECLARE #Ded AS NVARCHAR(MAX)
SET #Ded = STUFF((SELECT ', ISNULL( ' + QUOTENAME(c.shortname) + ', 0.00 )AS ' +
QUOTENAME(c.shortname) FROM (SELECT DISTINCT shortname FROM #Temp
WHERE ISNULL(shortname,'') <> '' AND Adtype = 2) AS c ORDER BY
shortname FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #Query = 'SELECT CAST(ROW_NUMBER() OVER(ORDER BY EmpNo ASC) AS
VARCHAR(100)) AS [S.No],EmpNo,Name,' + #Ded +' FROM #Temp
PIVOT(SUM(Amount) FOR shortname IN (' + #Ded + ')) AS PVTTable'
EXEC sp_executesql #Query
But it displays the following error, and line 3 doesn't not have a "(".
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '('.
Any help to solve this problem would be appreciated.
Problem is with #der variable use in in clause.
you are setting column name with isnull and in in clause, it is not supported.
Please try below query.
;with tbl1 as
(
select 1 EmpNo,'Emp1' FirstName
union all
select 2 EmpNo,'Emp2' FirstName
),
tbl2 as
(
select 'EMP1' shortname,100 Amount, 2 Adtype,1 EmpNo
union all
select 'EMP2' shortname,100 Amount, 2 Adtype,2 EmpNo
)
SELECT DISTINCT hdr.EmpNo,hdr.FirstName AS Name,
ISNULL(TBL.shortname,'')AS shortname,
ISNULL(TBL.Amount,0.00) AS Amount,
TBL.Adtype INTO #Temp FROM tbl1 AS hdr
LEFT JOIN tbl2 TBL ON TBL.EmpNo = hdr.EmpNo
DECLARE #Ded AS NVARCHAR(MAX)='' ,#Query AS NVARCHAR(MAX)=''
DECLARE #Wer AS NVARCHAR(MAX)=''
SET #Ded = STUFF((SELECT ', ISNULL( ' + QUOTENAME(c.shortname) + ', 0.00 )AS ' +
QUOTENAME(c.shortname) FROM (SELECT DISTINCT shortname FROM #Temp
WHERE ISNULL(shortname,'') <> '' AND Adtype = 2) AS c ORDER BY
shortname FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #Wer = STUFF((SELECT ', ' + QUOTENAME(c.shortname) FROM (SELECT DISTINCT shortname FROM #Temp
WHERE ISNULL(shortname,'') <> '' AND Adtype = 2) AS c ORDER BY
shortname FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #Query = 'SELECT CAST(ROW_NUMBER() OVER(ORDER BY EmpNo ASC) AS
VARCHAR(100)) AS [S.No],EmpNo,Name,' + #Ded +' FROM #Temp
PIVOT(SUM(Amount) FOR shortname IN (' + #Wer + ')) AS PVTTable'
--print #Query
EXEC sp_executesql #Query

Dynamic Pivot Results to a Temp Table

While I was able to find how to pivot this data in these forums, I have not been able to find a means to push the results to a temp table so that I can use it for other queries. The code is the following. Is there a possible way to have the output of this populate a temp table?
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(QT.QUESTION_DESC)
FROM #QUES_TEMP QT
GROUP BY QT.QUESTION_DESC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT EVAL_ID, AuditType, ' + #cols + '
into ##tmp
from
(
select QT.EVAL_ID,
QT.AuditType,
QT.SCORE,
QT.QUESTION_DESC
from #QUES_TEMP QT
) x
pivot
(
max(SCORE)
for QUESTION_DESC in (' + #cols + ')
) p '
execute(#query);
select * from ##tmp
You should be able to use INTO Clause. I added INTO into your example.
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(QT.QUESTION_DESC)
FROM #QUES_TEMP QT
GROUP BY QT.QUESTION_DESC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT EVAL_ID, AuditType, ' + #cols + ' from
(
select QT.EVAL_ID,
QT.AuditType,
QT.SCORE,
QT.QUESTION_DESC
into ##tmp
from #QUES_TEMP QT
) x
pivot
(
max(SCORE)
for QUESTION_DESC in (' + #cols + ')
) p '
execute(#query);
SELECT * FROM ##tmp
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(QT.QUESTION_DESC)
FROM #QUES_TEMP QT
GROUP BY QT.QUESTION_DESC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT EVAL_ID, AuditType, ' + #cols + '
from
(
select QT.EVAL_ID,
QT.AuditType,
QT.SCORE,
QT.QUESTION_DESC
from #QUES_TEMP QT
) x
pivot
(
max(SCORE)
for QUESTION_DESC in (' + #cols + ')
) p '
set #query = 'select * into ##Temp from ('+#query+') y'
execute(#query)
select * from ##Temp

while converting column to row not able to fetch value from another table automatically

select *
from (
select vtid, convert(date, dtime) as Date from Transaction_tbl where locid = 5
) as vt
pivot (
count(vtid)
for vtid in (select vtid from VType_tbl)
) as pvt
while executing this query am getting error
Incorrect syntax near the keyword 'select'." and Incorrect syntax near
')'.
actually I have one more table,name= Vtype_table , How Can I load all vtid from vtype table in this query? I want to get output depend upon vtid.
Any help greatly appreciated.
Your PIVOT syntax is correct except you are using a SELECT statement inside your PIVOT.
You cannot use a SELECT statement inside the PIVOT IN clause to select column headers. It is required that the columns for the IN clause be known prior to executing the query.
If you are looking to generate a dynamic list of vtid values, then you will need to use dynamic SQL to get the result and the syntax will be similar to the following:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(vtid)
from VType_tbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Date, ' + #cols + '
from
(
select vtid, convert(date, dtime) as Date
from Transaction_tbl
where locid = 5
) d
pivot
(
count(vtid)
for vtid in (' + #cols + ')
) p '
execute(#query);
Edit, if you want the type names to appear then you should be able to use the following:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(vt_name)
from VType_tbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Date, ' + #cols + '
from
(
select v.vt_name, convert(date, dtime) as Date
from Transaction_tbl t
inner join VType_tbl v
on t.vtid = v.vtid
where locid = 5
) d
pivot
(
count(vt_name)
for vt_name in (' + #cols + ')
) p '
execute(#query)
Note: I am guessing on the column name for VType_tbl