How can I add this additional column based on condition

Rehan Mubarak 20 Reputation points
2023-09-15T16:56:10.4+00:00

Hi Team,

I want to write a query for my input table and add a additional column on fly if parent question response satisfy the condition mentioned in the child question. Below is sample result that I want to achieve.

Please help.

User's image

Azure SQL Database
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,159 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 118.5K Reputation points
    2023-09-15T18:42:52.5666667+00:00

    Try something like this:

    select Q.*, 
        case when P.QuestionId is null then 'Y'
        else
            case Q.Condition 
            when '=' then iif(P.QuestionResponse = Q.ParentResponse, 'Y', 'N') 
            when '>' then iif(P.QuestionResponse > Q.ParentResponse, 'Y', 'N') 
            end
        end as ShowQuestion
    from Questions Q
    left join Questions P on P.QuestionId = Q.ParentQuestionId
    

    It can be extended for more supported conditions.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.