0

I am using Microsoft SQL Server and pyodbc

My tables:

enter image description here

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.

Rina Tse
  • 61
  • 5
  • 1
    The simplified version of your table is difficult to understand. Could you simplify it more? The best way is sharing some sample data and expected output. – James May 25 '22 at 21:52
  • For dynamic pivotting could you check https://stackoverflow.com/questions/71483504/sql-server-pivot-with-multiple-rows-output/71485354#71485354 ? – Umut TEKİN May 26 '22 at 08:51

0 Answers0