SQL Pivot Query - sql

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

Related

How to pivot Weekend Dates as column dynamically in SQL

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;

Is there any way to create View or temp table from dynamic SQL query

I have a query that provides some data I want to save this data in a temp table or view. Please help
The query is given below:
IF OBJECT_ID('tempdb..#NLSPMTS3_tmp') IS NOT NULL
DROP TABLE #NLSPMTS3_tmp
SELECT *
INTO #NLSPMTS3_tmp
FROM vwNLSPayments4
DECLARE #Columns AS VARCHAR(MAX)
SELECT #Columns = COALESCE(#Columns + ', ','') + QUOTENAME(b.mop_fpd)
FROM (SELECT DISTINCT mop_fpd FROM #NLSPMTS3_tmp) AS B
ORDER BY B.mop_fpd
-- You can't remove nulls from a PIVOT, so you have to create a second set of column names
DECLARE #NullColumns as VARCHAR(MAX)
SELECT #NullColumns =
COALESCE(#NullColumns + ', ','') + 'ISNULL(' + QUOTENAME(b.mop_fpd) + ', 0) ' + QUOTENAME(b.mop_fpd)
FROM (Select DISTINCT mop_fpd FROM #NLSPMTS3_tmp) AS B
ORDER BY B.mop_fpd
DECLARE #SQL as NVARCHAR(MAX)
SET #SQL = 'SELECT acctrefno, ' + #NullColumns + '
FROM
(SELECT payment_amount, acctrefno, mop_fpd
FROM
nlsdev.dbo.vwnlsPayments2
) as PivotData
PIVOT
(sum(payment_amount) FOR mop_fpd IN (' + #Columns + ')) AS PivotResult ORDER BY acctrefno'
EXEC (#SQL)
I just simply put create a view as <above SQL query> but it did not work.

is any other way to do in dynamic pivot

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

PIVOT and TEMP TABLE

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

How to Perform Explicit Conversion in Dynamic Pivot

How to Perform Explicit Conversion in Dynamic Pivot.
I need to convert datatype for single field.
This is my sample query
SELECT #cols = STUFF((SELECT ',' + (QUOTENAME(P.ColumnName))from #temp as p
JOIN information_schema.columns as C ON P.ColumnName=C.column_name
where C.table_name='tablename'
SET #query = 'SELECT ' + #cols + 'from (select ColumnVlaue, ColumnName from #temp) x
pivot(max(ColumnVlaue) for ColumnName in (' + #cols + ')) p '
EXECUTE(#query)
You do it when you build the #cols variable.
Actually you need a second #cols variable #cols2 that holds the columns with the cast expression.
If #cols contains Col1, Col2 then #Cols2 should be cast(Col1 as int) as Col1, cast(Col2 as int) as Col2
Use #Cols2 in the select column list and #Cols in the pivot column list.
SET #query = 'SELECT ' + #cols2 + 'from (select ColumnVlaue, ColumnName from #temp) x
pivot(max(ColumnVlaue) for ColumnName in (' + #cols + ')) p '
EXECUTE(#query)