I have tried a couple of combinations to wrap the last select to use PIVOT with its result
This is the code
DECLARE #cols VARCHAR(1000)
DECLARE #sqlquery VARCHAR(2000)
SELECT #cols = STUFF(( SELECT distinct ',' + QuoteName(idIndice)
FROM tgpwebged.dbo.sistema_Indexacao as a FOR XML PATH('')
), 1, 1, '')
SET #sqlquery = 'WITH TempTable AS
(
select distinct a.id, b.idIndice, b.valor
from tgpwebged.dbo.sistema_Documentos as a
join tgpwebged.dbo.sistema_Indexacao as b on a.id = b.idDocumento
join tgpwebged.dbo.sistema_DocType as c on a.idDocType = c.id
join tgpwebged.dbo.sistema_DocType_Index as d on c.id = d.docTypeId
where d.docTypeId = 40
and (b.idIndice = 11 AND b.valor = ''11111111'' OR b.idIndice = 12 AND b.valor = ''11111'' )
)
SELECT * FROM TempTable t1
WHERE ((select count(*)
from TempTable t2
where t1.id = t2.id AND t1.valor != t2.valor) = 1)base
PIVOT
(
Max(valor)
FOR [idIndice] IN (' + #cols + ')
) AS finalpivot'
EXECUTE ( #sqlquery )
This of course will not work so do I need to enclose parentheses or somenthing like that to get it done???
Try replace EXECUTE ( #sqlquery ) on EXEC #sqlquery
more info about EXECUTE statement
Related
I have a XML transposing rows into column query. I am trying to insert the data to a table that is created dynamically. However, I am getting error saying conversion failed when converting nvarchar value to data type int when I execute '#query'
This is my current code:
DECLARE #cols NVARCHAR(MAX), #cols1 NVARCHAR(MAX), #query NVARCHAR(MAX);
SET #cols = STUFF(
(
SELECT
','+QUOTENAME(c.[destfieldname] ) + c.datatype
FROM #specnorm c
left join #rawtemp d on c.fieldname = d.fieldname
group by c.destfieldname, c.datatype
order by min(sourceSequenceTypical)
for xml path ('')),1,1,'')+ ', [sequenceID] int, [subsequenceID] int';
SET #cols1 = STUFF(
(
SELECT
','+QUOTENAME(c.[destfieldname] )
FROM #specnorm c
left join #rawtemp d on c.fieldname = d.fieldname
group by c.destfieldname
order by min(sourceSequenceTypical)
for xml path ('')),1,1,'')+ ', [sequenceID],
[subsequenceID] ';
SET #query = ' SELECT '+#cols1+' from (SELECT
c.[rownumber],
c.[contents],
d.[destfieldname]
FROM #rawtemp c
left join #specnorm d on c.fieldname = d.fieldname
)x pivot (max(contents) for destfieldname in ('+#cols1+')) p'
exec ('CREATE Table dbo.sample' + ' (' +#cols + ')');
exec ('Insert into dbo.sample' + #query)
try:
SET #query = 'SELECT '+#cols+' into YOURTABLE from (SELECT
[rownumber],
[contents],
[fieldname]
FROM #rawtemp
) x pivot (max(contents) for fieldname in ('+#cols+')) p'
it creates YOURTABLE on the fly
I have a CTE table which returns dynamic SQL.
Here is my CTE query:
DECLARE #Qry VARCHAR(MAX)
;WITH CTE AS
(
SELECT
Qry = 'UPDATE data_'+ REPLACE(mrp.father_uid, '-', '_')+' SET done = 2 WHERE uid = '''+ CAST(mrp.uid AS VARCHAR(250)) + ''''
FROM
[4928_MyProcessDB].dbo.main_result_process mrp WITH (NOLOCK)
INNER JOIN
[4928_MyProcessDB].dbo.main_result_process_part mrpp WITH (NOLOCK) ON mrp.uid = mrpp.process_uid
)
SELECT *
FROM CTE
which returns:
I want to execute each row on the CTE table. How can I do that?
With just a couple of tweaks
DECLARE #Qry VARCHAR(MAX) = ''
;WITH CTE AS
(
SELECT
Qry = ';UPDATE data_'+ REPLACE(mrp.father_uid, '-', '_')+' SET done = 2 WHERE uid = '''+ CAST(mrp.uid AS VARCHAR(250)) + ''''
FROM
[4928_MyProcessDB].dbo.main_result_process mrp WITH (NOLOCK)
INNER JOIN
[4928_MyProcessDB].dbo.main_result_process_part mrpp WITH (NOLOCK) ON mrp.uid = mrpp.process_uid
)
SELECT #Qry = #Qry + Qry
FROM CTE
Exec(#Qry)
I Have one CTE Query
WHICH Return This Output :-
I Have Another SQL Statement(With Pivot Query) Which has Following Output :-
I Want to Join Both Output in Single Query output.
I Have Tried to JOIN This Both Query. but, I can't.
I need to show TotalTraffic and UniqueAttendee(both column) output with Pivot table Output.
I want both output in one table format to show it.
my Code is below for both Output:
---output 1 Query(CTE):
;WITH Detailstbl AS (
SELECT
[S].[Title]
,COUNT([VAL].[UserID]) [TotalTraffic]
,COUNT(DISTINCT [VAL].[UserID]) [UniqueAttendee]
FROM [dbo].[AC_Session] [S]
INNER JOIN
[dbo].[AC_ViewActivityLogs] [VAL] ON [S].[SessionID] = [VAL].[ObjectID] AND [VAL].[ObjectName] = 'View Poster Session'
WHERE [S].[IsPosterType] = 1
GROUP BY [S].[Title]
)
SELECT * FROM Detailstbl;
---output 2 Query(Pivot):
DROP TABLE #tempTable
CREATE TABLE #tempTable
(
Title nvarchar(MAX),
TotalTraffic int,
viewdate nvarchar(50)
)
--inserthere
INSERT INTO #tempTable (Title,TotalTraffic,viewdate)
SELECT [S].[Title]
,COUNT([VAL].[UserID]) [TotalTraffic]
,CONVERT(VARCHAR(10), [ViewedOn], 101) AS [ViewedDate]
FROM [dbo].[AC_Session] [S]
INNER JOIN
[dbo].[AC_ViewActivityLogs] [VAL] ON [S].[SessionID] = [VAL].[ObjectID] AND [VAL].[ObjectName] = 'View Poster Session'
WHERE [S].[IsPosterType] = 1
GROUP BY [S].[Title],CONVERT(VARCHAR(10), [ViewedOn], 101)
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.viewdate)
FROM #tempTable c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
PRINT #cols
set #query = '
SELECT * FROM (
SELECT Title,
' + #cols + ' from
(
select
Title,
TotalTraffic,
viewdate
from #tempTable
) x
pivot
(
max(TotalTraffic)
for viewdate in (' + #cols + ')
) p
) AS x '
execute(#query)
PRINT #query
Below what I have tried but getting error Incorrect syntax near ON
set #query = '
SELECT *
FROM Detailstbl
INNER JOIN(
SELECT * FROM (
SELECT Title,
' + #cols + ' from
(
select
Title,
TotalTraffic,
viewdate
from #tempTable
) x
pivot
(
max(TotalTraffic)
for viewdate in (' + #cols + ')
) p
) AS x ON Detailstbl.Title = x.Title
)'
execute(#query)
PRINT #query
The place where you written the On Clause is incorrect. it should be after the last ')' and you can't use the CTE inside this Dynamic SQL. better try to insert the CTE data into a TempTable Named #Detailstbl
Temp table
SELECT
[S].[Title]
,COUNT([VAL].[UserID]) [TotalTraffic]
,COUNT(DISTINCT [VAL].[UserID]) [UniqueAttendee]
INTO #Detailstbl
FROM [dbo].[AC_Session] [S]
INNER JOIN
[dbo].[AC_ViewActivityLogs] [VAL] ON [S].[SessionID] = [VAL].[ObjectID] AND [VAL].[ObjectName] = 'View Poster Session'
WHERE [S].[IsPosterType] = 1
GROUP BY [S].[Title]
Dynamic SQL
set #query = '
SELECT *
FROM #Detailstbl dtbl
INNER JOIN(
SELECT * FROM (
SELECT Title,
' + #cols + ' from
(
select
Title,
TotalTraffic,
viewdate
from #tempTable
) x
pivot
(
max(TotalTraffic)
for viewdate in (' + #cols + ')
) p
) dt
) x ON dtbl.Title = x.Title '
I need to Pivot Questions With Their Answers.The Desired Output of the pivot Query is below and the table structure too.
I have Created the SQL fiddle Here Sql Fiddle. I saw many examples of count with pivot but couldn't find something similar to this.
You simply need some joins to get the base data and a dynamic pivot to show the result in the desired format.
try the following:
drop table if exists #temp
--base table with all details
select s.ID SurveyID, s.SubmittedBy, sq.Question, sa.Answer
into #temp
from #Survey s
join #SurveyMaster sm on sm.ID = s.SurveyMasterID
join #SurveyQuestion sq on sq.SurveyMasterID = s.SurveyMasterID
join #SurveyAnswers sa on sa.SurveyQuestionID = sq.ID and sa.SurveyID = s.ID
--dynamic pivot
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.Question)
FROM #temp c
ORDER BY 1 DESC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT SurveyID, SubmittedBy, ' + #cols + ' from
(
select SurveyID, SubmittedBy, Question, Answer
from #temp
) x
pivot
(
max(Answer)
for Question in (' + #cols + ')
) p '
--execution
execute(#query)
Please find the db<>fiddle here.
declare #sqlstring as varchar(max) = '';
SELECT
#sqlstring = STUFF((
SELECT distinct
',' + '[' + isnull(sq.Question, '''') + ']'
from
#surveyanswers sa
join
#SurveyQuestion sq
on sq.ID = sa.SurveyQuestionID
join
#survey sv
on sv.SurveyMasterID = sq.SurveyMasterID FOR XML PATH('')), 1, 1, '')
select
sa.SurveyID,
sv.SubmittedBy,
sq.Question,
sa.Answer into ##temp
from
#surveyanswers sa
join
#SurveyQuestion sq
on sq.ID = sa.SurveyQuestionID
join
#survey sv
on sv.SurveyMasterID = sq.SurveyMasterID
set
#sqlstring = 'SELECT SurveyID,SubmittedBy,' + #sqlstring + ' FROM (select * from ##temp ) t ' + ' PIVOT ( ' + ' max(Answer) FOR Question IN (' + #sqlstring + ' ) ) AS pivot_table' execute(#sqlstring);
RESULT:
I was trying to create a Common Table Express(CTE) to store some data that I need which requires a bunch of inner join. Then, I would like to pivot the result using dynamic pivot columns. I wrote the query below but I'm getting the error
"Common table expression defined but not used."
How can I create a pivot query base on a CTE? By the way, I can do it without the CTE but I would like to know if I can do it with CTE.
DECLARE #cols nvarchar(max)
DECLARE #sql nvarchar(max)
SELECT #cols = isnull(#cols + ', ', '') + '[' + Convert(varchar(max),T.CostCenterNumber) + ']' FROM (SELECT distinct CostCenterNumber FROM CostCenters) as T
;With PivotData as (
SELECT B.[Year], C.CostCenterNumber, C.CostCenterName, E.[Description] as GLClass, D.Code, D.[GLDescription], A.Total
From GeneralLedgers A inner join
Years B on A.YearID = B.ID
inner join CostCenters C on
A.CostCenterID = C.ID
inner join GLCodes D on
A.GLCodeID = D.ID inner join
GLClassificationTypes E on
D.GLClassificationTypeID = E.ID)
SELECT #sql = '
Select *
From(
SELECT [Year], CostCenterNumber, GLClass, Code, GLDescription, Total
FROM PivotData) as T
PIVOT
(
Max(Total)
for [CostCenterNumber] in (' + #cols + ')
)) as P'
EXEC(#sql)
Here is how you can do it. I have written the logic inside the query
DECLARE
#cols nvarchar(max),
#stmt nvarchar(max)
SELECT #cols = isnull(#cols + ', ', '') + '[' + Convert(nvarchar(max),T.CostCenterNumber)+ ']'
FROM (SELECT distinct CostCenterNumber FROM CostCenters) as T
SELECT #stmt = '
-- Your CTE goes here
;WITH CTE AS
(
SELECT [Year], E.[Description] as GLClass, Code,
GLDescription, CostCenterNumber, Total
FROM GeneralLedgers A inner join
Years B on A.YearID = B.ID inner join
GLCodes C on A.GLCodeID = C.ID inner join
CostCenters D on A.CostCenterID = D.ID inner join
GLClassificationTypes E on C.GLClassificationTypeID = E.ID
)
-- Pivoted reuslt
SELECT * FROM
(
-- Here you select the data from CTE
SELECT *
FROM CTE
)as T
PIVOT
(
max(T.Total)
for T.[CostCenterNumber] in (' + #cols + ')
) as P'
exec sp_executesql #stmt = #stmt