Erica
Erica

Reputation: 1

Trying to get column value to only return the column it references to it in the same table in sql

The values in AnswerInt is a number 1 through 5. The number goes with the column LabelText number.

I want to get the column AnswerInt to return and then only the column LabelText it references.

SELECT
    Question,
    AnswerInt,
    AnswerText,
    CreatedTime,
    LabelText1,
    LabelText2,
    LabelText3,
    LabelText4,
    LabelText5,
    SurveyType,
    ResponseTypeDesc,

FROM
    dbo.WEBSITE_SURVEYS

WHERE
    CASE AnswerInt 
        WHEN '1' THEN 'LabelText1'
        WHEN '2' THEN 'LabelText2'
        WHEN '3' THEN 'LabelText3'
        WHEN '4' THEN 'LabelText4'
        WHEN '5' THEN 'LabelText5'

Upvotes: 0

Views: 44

Answers (3)

Olga Romantsova
Olga Romantsova

Reputation: 1081

If the number in AnswerInt column goes with the column LabelText number then try this simple query:

select 
    Question,
    AnswerInt,
    AnswerText,
    CreatedTime,
    SurveyType,
    ResponseTypeDesc,
    CONCAT('LabelText', AnswerInt)LabelText
FROM
    dbo.WEBSITE_SURVEYS

Upvotes: 0

Thom A
Thom A

Reputation: 95906

As you have a number to define the value returned, which relates to the column, you could use CHOOSE here; which is effectively a shorthand CASE expression:

SELECT Question,
       AnswerInt,
       AnswerText,
       CreatedTime,
       SurveyType,
       ResponseTypeDesc,
       CHOOSE(AnswerInt, LabelText1, LabelText2, LabelText3, LabelText4, LabelText5) AS LabelText
FROM dbo.WEBSITE_SURVEYS;

Upvotes: 1

Rudey
Rudey

Reputation: 4965

Did you mean to put the CASE expression in the SELECT clause?

SELECT
    Question,
    AnswerInt,
    AnswerText,
    CreatedTime,
    SurveyType,
    ResponseTypeDesc,
    CASE AnswerInt
        WHEN '1' THEN LabelText1
        WHEN '2' THEN LabelText2
        WHEN '3' THEN LabelText3
        WHEN '4' THEN LabelText4
        WHEN '5' THEN LabelText5
    END AS LabelText

FROM
    dbo.WEBSITE_SURVEYS

Upvotes: 0

Related Questions