I am using Microsoft SQL Server and pyodbc
My tables:
I am trying to replicate the logic of a stored procedure in python, which dynamically pivots the result table per question_id.
In python, I am aiming to build columns for each QuestionId that stores Answer_Value, which is either a numerical answer to the question, the value -1 if that question was not answered or NULL if that question does not appear in the survey, per UserId
So far, I have:
for b in currentSurveyIDs:
survey = (b[0])
questions = (b[1])
InSurvey = (b[2])
allUserID = cursor.execute("""SELECT UserId FROM dbo.[Answer ]""").fetchall()
for i in allUserID:
userId = i[0]
if InSurvey == 1:
strQueryTemplateForAnswerColumn = cursor.execute("""SELECT COALESCE
((SELECT
a.UserId
FROM dbo.Answer a
WHERE a.UserId = ?
AND a.SurveyId = ?
AND a.QuestionId = ?
),-1) AS ANS_Q?""", userId, survey, questions,
questions).fetchall()
elif InSurvey == 0:
strQueryTemplateForNullColumnn = cursor.execute(""" SELECT NULL AS
ANS_?""",questions).fetchall()
currentSurveyIds is from another query that returns if a question was in the survey or not.
So far, I am able to return the answer or -1 for each question in a single column or NULL for each question in a single column
I am not sure what the next step is to recreate the dynamic pivot that would result in, for example:
Question1| Question2| Question3
2 -1 NULL
4 3 NULL
where the number of columns is dynamic.
Thank you for any input.