I am making attempts to run my first dynamic pivot in SQL Server 2012.
My #temp table that I am using for the dynamic pivoting looks like this.
YearMonth Agreement nr Discount
------------------------------------
201303 123 1
201303 12 0
201304 1 0
I am running this code and it does not work:
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName = ISNULL(#ColumnName + ',', '') + QUOTENAME(YearMonth )
FROM (SELECT DISTINCT YearMonth FROM #FINAL) AS Courses
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT [Agreement nr],YearMonth , ' + #ColumnName + '
FROM #FINAL
PIVOT(
COUNT(agreement nr)
FOR YearMonth IN (' + #ColumnName + ') AS PVTTable'
--Execute the Dynamic Pivot Query
EXECUTE #DynamicPivotQuery;
The error message I am getting is
FOR YearMonth IN ([201403]) AS PVTTable' is not a valid identifier.
What am I missing here?
The cause of the error is that you're missing a parenthesis before you alias the Pivot. More than this however your pivot was rather inefficient.
You should select what you need for the source table in your pivot otherwise it could run for a long time and produce a lot of rows with null returns.
The below is fixed and hopefully more efficient:
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(YearMonth )
FROM (SELECT DISTINCT YearMonth FROM #FINAL) AS Courses
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT ' + #ColumnName + '
FROM (Select [Agreement nr], YearMonth from #FINAL) src
PIVOT(
COUNT([Agreement nr])
FOR YearMonth IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXECUTE sp_executesql #DynamicPivotQuery;
You forgot to close pivot.
PIVOT(
COUNT(Kundavtalid)
FOR YearMonth IN (' + #ColumnName + ')
) AS PVTTable' -- here you miss pathernesis
You are missing a parenthesis
SET #DynamicPivotQuery =
N'SELECT [Agreement nr],YearMonth , ' + #ColumnName + '
FROM #FINAL
PIVOT(
COUNT([agreement nr])
FOR YearMonth IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
Related
I have a dynamic SQL Query that is providing the correct data but I have extra rows appearing, I'm not sure why. Query is this
-- Nuke the temp DB if it already exists
IF OBJECT_ID('tempdb..##TBL_TEMP') IS NOT NULL
DROP TABLE ##TBL_TEMP
--Parameter to hold dynamically created SQL Script
declare #sqlquery as nvarchar(max)
--Parameter to hold the Pivoted Column Values
declare #pivotcolumns as nvarchar(max)
--generate list of territories that will become column names
select #pivotcolumns = coalesce(#pivotcolumns + ',','') + quotename(Territory)
from
(SELECT DISTINCT TERRITORY FROM LiveGAPDetailedBudget
where res_id = '160') AS X
--select #pivotcolumns
--create dynamic query with all values for pivot at runtime
set #sqlquery = 'SELECT [ProductCategory] AS "Product Category",' + #pivotcolumns +' INTO ##TBL_TEMP
FROM LiveGAPDetailedBudget
PIVOT (MAX([Budget])
FOR [Territory] IN (' + #pivotcolumns +')) AS T WHERE res_id = 160'
--select #sqlquery
--Execute Dynamic Query
EXEC sp_executesql #sqlquery
--View results in temp table
SELECT * FROM ##TBL_TEMP order by [Product Category]
The output from the query is linked - I can't for the life of me get these rows consolidated to eliminate nulls....see link below
You are selecting extra columns that you are not required for pivoting.
change your query to
set #sqlquery = 'SELECT [ProductCategory] AS "Product Category",'
+ #pivotcolumns
+ ' INTO ##TBL_TEMP
FROM (
SELECT [ProductCategory], [Territory], [Budget]
FROM LiveGAPDetailedBudget
WHERE res_id = 160
) AS D
PIVOT (MAX([Budget])
FOR [Territory] IN (' + #pivotcolumns +')) AS T '
I am trying to insert the result of the sql dynamic into a temp table but i am getting a syntax error. I have researched and i am not able to figure what i am doing wrong here
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName = ISNULL(#ColumnName + ',','') + QUOTENAME([month])
FROM (SELECT DISTINCT [Month] FROM MyTable) AS [Month]
order by [month]
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT Mem_Name, ' + #ColumnName + '
FROM MyTable into MyTest
PIVOT(SUM(Amount)
FOR Month IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
all what i had to do is add this:
' into ##myTempTable
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName = ISNULL(#ColumnName + ',','') + QUOTENAME([month])
FROM (SELECT DISTINCT [Month] FROM MyTable) AS [Month]
order by [month]
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT Mem_Name, ' + #ColumnName + ' into ##myTempTable
FROM MyTable
PIVOT(SUM(Amount)
FOR Month IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
I need to use pivot to create time table from the following data:
I'm using this query
select
start_time, end_time, s.subj_name, tt.dd
from
time_table tt
inner join
subj s on tt.subjid = s.subjid
I am able to pivot my result to
I used following SQL code to do that:
--Declare necessary variables
DECLARE #SQLQuery AS NVARCHAR(MAX)
DECLARE #PivotColumns AS NVARCHAR(MAX)
--Get unique values of pivot column
SELECT #PivotColumns = COALESCE(#PivotColumns + ',','') + QUOTENAME(dd)
FROM (SELECT DISTINCT(dd)
FROM time_table tt
WHERE divid = 1 AND tt.active = 1) AS PivotExample
SELECT #PivotColumns
--Create the dynamic query with all the values for
--pivot column at runtime
SET #SQLQuery =
N'SELECT start_time,end_time, ' + #PivotColumns + '
FROM [dbo].[time_table]
PIVOT( SUM(subjid)
FOR dd IN (' + #PivotColumns + ')) AS P'
SELECT #SQLQuery
--Execute dynamic query
EXEC sp_executesql #SQLQuery
Do help me out to get subjectname as value instead of subjectid
Since you are pivoting a VARCHAR, you can't use SUM, but have to use MAX or MIN
Try instead:
SET #SQLQuery =
N'SELECT start_time,end_time, ' + #PivotColumns + '
FROM [dbo].[time_table]
PIVOT( MAX(subjectname)
FOR dd IN (' + #PivotColumns + ')) AS P'
Found answer for it which provides simpler way to get it.
click to get answer
while answering one question i got struck with other question in mind.when it is normal pivot it is working fine but if i'm trying to do Dynamic query when the problem arises
after answering he asked for Dynamic Pivot
PIVOT the date column in SQL Server 2012
if OBJECT_ID('tempdb..#temp') is not null
begin
drop table #temp
end
CREATE table #temp (dated varchar(10),E1 int,E2 int,E3 int,E4 int)
insert into #temp
(dated,E1,E2,E3,E4)values
('05-27-15',1,1,2,3),
('05-28-15',2,3,NULL,5),
('05-29-15',3,4,null,2)
DECLARE #statement NVARCHAR(max)
,#columns NVARCHAR(max)
SELECT #columns = ISNULL(#columns + ', ', '') + N'[' + tbl.dated + ']'
FROM (
SELECT DISTINCT dated
FROM #temp
) AS tbl
SELECT #statement = 'Select P.col,MAX('+#columns+') from (
select col,' + #columns + ' from (
select * from #temp
CROSS APPLY(values(''E1'',E1),(''E2'',E2),(''E3'',E3),(''E4'',E4))cs (col,val))PP
PIVOT(MAX(val) for dated IN (' + #columns + ')) as PVT)P
GROUP BY P.COL
'
PRINT #statement
EXEC sp_executesql #statement = #statement
my problem is how can i take MAX() conditions for the all dates dynamically like
max(05-27-15),max(05-28-15) etc dates are coming dynamically how to assign max condition
Moving the MAX aggregate to column list variable will fix the issue
DECLARE #statement NVARCHAR(max),
#columns NVARCHAR(max),
#select_columns NVARCHAR(max)
SELECT #select_columns = Isnull(#select_columns + ', ', '')+ N'MAX([' + tbl.dated + '])'
FROM (SELECT DISTINCT dated
FROM #temp) AS tbl
SELECT #columns = Isnull(#columns + ', ', '') + N'[' + tbl.dated+ ']'
FROM (SELECT DISTINCT dated
FROM #temp) AS tbl
SELECT #statement = 'Select P.col,' + #select_columns
+ ' from (
select col,' + #columns
+ ' from (
select * from #temp
CROSS APPLY(values(''E1'',E1),(''E2'',E2),(''E3'',E3),(''E4'',E4))cs (col,val))PP
PIVOT(MAX(val) for dated IN (' + #columns
+ ')) as PVT)P
GROUP BY P.COL
'
PRINT #statement
EXEC sp_executesql #statement = #statement
I have the below data in SQL:
Now, I would like to pivot it base on the "CostCenterNumber" field to obtain this:
Try this one:
DECLARE #cols as varchar(max)
DECLARE #sql as varchar(max)
SELECT #cols = coalesce(#cols + ',','') + '[' + CostCenterNumber + ']' FROM #MyTable
SET #sql =
'SELECT Year, GLClass, Code, GLDescription, ' + #cols + '
FROM (
SELECT *
FROM #MyTable
) as P
PIVOT
(
SUM(Total)FOR [CostCenterNumber] IN (' + #cols + ')
)AS pvt'
EXEC(#sql)
I suggest you to use where and between condition from your query