I have a #temp table output, which I am trying to bring the weekend dates as columns.
When I run the query I get this error "Parse error at line: 5, column: 34: Incorrect syntax near '2022'.", Can someone please help with what I am doing wrong?
Thanks in advance.
#TABLE OUTPUT
DECLARE #col NVARCHAR(MAX);
DECLARE #sql NVARCHAR(MAX);
SET #col =
(
SELECT STRING_AGG(t.[WeekEnd], ',')
FROM
(SELECT DISTINCT [WeekEnd] FROM #TABLE) AS t
);
SET #sql
= 'Select *, ' + #col+ '
from
(select #TABLE.PTLITNBR,#TABLE.PTLWHSE,#TABLE.PTLDATATYPE,#TABLE.WeekEnd,#TABLE.Orders from #TABLE) as t
PIVOT
(MAX(Orders) for WeekEnd in (' + #col + N')) as Pivot_Table';
EXECUTE (#sql);
DECLARE #cols AS NVARCHAR(MAX)
, #query AS NVARCHAR(MAX);
SET #cols =
(
SELECT string_agg(CONVERT(NVARCHAR(MAX), QUOTENAME(TempTb.WeekEnd)), ', ')
FROM
(SELECT DISTINCT WeekEnd FROM #temp1) TempTb --distinct weekend dates selected as there a
);
SET #query
= N'SELECT p.PTLWHSE, p.PTLITNBR, p.PTLDATATYPE, ' + #cols
+ N' from
(
select PTLWHSE,PTLITNBR,PTLDATATYPE,WeekEnd, Orders
from #temp1 AS TempTb
) x
pivot
(
max(Orders)
for WeekEnd in (' + #cols + N')
) p ';
EXEC sp_executesql #query;
Related
Hello everyone and thanks in advance.
I have two tables that I need to merge using Pivot.
1)Table with list of users:
#Tbl_staff(UserId INT,
Name NVARCHAR(MAX),
Surname NVARCHAR(MAX),
Level NVARCHAR (MAX)
)
2) Table with users' actions:
#Tbl_acts(Day DATE,
UserIdfk INT,
WorkedHours NVARCHAR(MAX),
Absence NVARCHAR(MAX),
Festivity NVARCHAR(2)
)
Table 2 has a complete month for each ID and for each day the action recorded. (Hours worked, hours of absence and type of absence, if the day is a holiday)..
It can also be null if in the db there is no action for that person on that day.
I wrote my Pivot like this:
DECLARE #columns NVARCHAR(MAX), #sql NVARCHAR(MAX);
SET #columns = N'';
SELECT #columns += N', p.' + QUOTENAME((cast(USERID AS VARCHAR(MAX)) + ' ' + NAME+ ' ' + SURNAME+' ' +(ISNULL (LEVEL,''))))
FROM (SELECT p.USERID,p.NAME,p.SURNAME,p.LEVEL FROM #TBL_STAFF AS p
INNER JOIN #TBL_ACTS AS o
ON p.USERID = o.USERIDFK
GROUP BY p.USERID,P.NAME,P.SURNAME,P.LEVEL) AS x;
SET #sql = N'
SELECT DAY,' + STUFF(#columns, 1, 2, '') + '
FROM
(
SELECT DISTINCT o.DAY,IDU = CAST(p.USERID AS NVARCHAR(MAX)), o.WORKEDHOURS
FROM #TBL_STAFF AS p, #TBL_ACTS AS o
where p.USERID= o.USERIDFK
) AS j
PIVOT
(
MAX(WORKEDHOURS) FOR IDU IN ('
+ STUFF(REPLACE(#columns, ', p.[', ',['), 1, 1, '')
+ ')
) AS p ORDER BY DAY;';
PRINT #sql;
EXEC sp_executesql #sql;
(Trying to show only the worked hours ... would be a good start)
It's the result: Column 'day' is ok(31 rows) and 'staff' too but it shows nothing inside it.
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
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
please can you help me put this script into a temp table. i have been working on this for hours and it keeps giving me errors.
DECLARE #PivotColumnHeaders VARCHAR(MAX)
SELECT #PivotColumnHeaders =
COALESCE(#PivotColumnHeaders + ',[' + CAST(expansion as varchar(max)) + ']',
'[' + CAST(expansio
n as varchar(max))+ ']')
INTO #temp
FROM (Select distinct expansion from #CD4_VL2) results
DECLARE #PivotTableSQL NVARCHAR(MAX)
SET #PivotTableSQL = N'
select * from
(
select subjectID,expansion,printableValue1
from #CD4_VL2) as results
PIVOT
(MAX([printableValue1])
FOR [expansion] IN (
' + #PivotColumnHeaders + '
)
) as PivotTable
--order by Performed_Date_And_Time desc
'
Execute(#PivotTableSQL )
Because you've pivoted on the expansion columns, the respective values of MAX(printableValue1) will now be in columns with the names of the data in the Expansion column. Change this like so:
DECLARE #PivotColumnHeaders NVARCHAR(MAX) = 'Expansion1, Expansion2, Expansion3';
DECLARE #PivotTableSQL NVARCHAR(MAX);
SET #PivotTableSQL =
N'select subjectID, ' + #PivotColumnHeaders
+' from #CD4_VL2
PIVOT
(
MAX([printableValue1])
FOR [expansion] IN (' + #PivotColumnHeaders + ')) x';
Execute(#PivotTableSQL);
SqlFiddle here