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
Related
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;
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.
I have a query that rotates a stock prices table, but it uses a temp table.
I would like to know how to store this rotated table in a table.
I have struggled to use this query with 'create table' because there is some variables declarations.
Here is the code:
IF OBJECT_ID('TEMPDB..#TEMP','U') IS NOT NULL DROP TABLE #TEMP;
DECLARE #COL NVARCHAR(MAX);
DECLARE #SQL NVARCHAR(MAX);
DECLARE #HEADER NVARCHAR(MAX);
DECLARE #FIX NVARCHAR(MAX);
DECLARE #VAR NVARCHAR(MAX);
DECLARE #ORDER NVARCHAR(MAX);
WITH
#TEMP AS(
select Cast(MarketDate as Date) as date_, oo.seccode, ConstFlag
FROM
(select distinct seccode, InfoCode, MarketDate, Constflag
from ds_russell1000_prices_adj_r) oo
SELECT * INTO #TEMP
FROM #TEMP
SET #FIX = 'Date_';
SET #VAR = 'Constflag'
SET #HEADER = 'seccode';
SELECT #COL = COALESCE(#COL + ',','') + QUOTENAME(seccode) FROM #TEMP F
GROUP BY QUOTENAME(seccode)
ORDER BY QUOTENAME(seccode)
SET #ORDER = 'Date_'
SET #SQL = 'SELECT ' + #FIX + ',' + #COL + ' FROM (SELECT ' + #FIX + ',' +
VAR + ', ' + #HEADER + ' FROM #TEMP) P
PIVOT (sum(' + #VAR + ') FOR ' + #HEADER + ' in (' + #COL + ')) PVT
ORDER BY ' + #ORDER + ''
EXEC sp_executesql #SQL;
IF OBJECT_ID('ds_russell1000_positions_ROTATED') IS NOT NULL DROP TABLE
ds_russell1000_positions_ROTATED;
select * into ds_russell1000_positions_ROTATED
from #TEMP
Could someone help please?
Instead of this line:
SELECT * INTO #TEMP
Simply replace #TEMP with the name of the permanent table you wish to create.
Also take the # sign off the name of your CTE:
WITH
TEMP AS(
...
FROM TEMP
# signs are for naming temporary tables and should not be used in other object names.
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