nitin
nitin

Reputation: 156

Select statement from sql table

enter image description here

Here is some QuestionID and OptionID with IsCorrect flag for every option, I am not getting a way to get the result set in the required format(shown in attached Image), it will be helpful if some one give some sort of suggestion with best way to achieve this, Thanks in Advance,

declare @temp table
(questionID int, optionID int, isCorrect bit, option_text varchar(50))

insert into @temp values
( 1, 1, 1, 'abc'), (1, 2, 1, 'pqr'), (1, 3, 0, 'mno' ),
(2, 1, 1, 'xyz' ), (2, 2, 1, 'def')

Upvotes: 0

Views: 100

Answers (2)

Mangal Pardeshi
Mangal Pardeshi

Reputation: 355

Try this:

SELECT T1.questionId  
           ,option_text = SubString (( SELECT ', ' + T2.option_text 

FROM @temp as T2 
WHERE T1.questionId = T2.questionId 
and  isCorrect = 1
FOR XML PATH ( '' ) ), 3, 1000) 
, 'key'as Answer

FROM @temp as T1 

GROUP BY questionId

union all 
select Questionid, Option_text, 'primary_key'
from @temp
order by 1

Create A Comma Delimited List From a Column

Upvotes: 1

jhmt
jhmt

Reputation: 1421

I think it's using GROUP_CONCAT function in SQL Server (2012?):
My answer is:
SQL Fiddle

SELECT 
questionID AS [QuestionID]
, option_text AS [OptionText]
, CASE WHEN (CHARINDEX(',', option_text) > 0) THEN 'key'
       WHEN (isCorrect = 1) THEN 'partial key'
       ELSE 'wrong key' END AS [Answere]
FROM
(
    SELECT questionID, option_text, isCorrect
    FROM @temp
    UNION ALL
    SELECT 
    questionID
    , LEFT(keys, LEN(keys) - 1)
    , isCorrect
    FROM
    (
        SELECT questionID
        , (SELECT option_text + ','
           FROM @temp
           WHERE questionID = t.questionID AND isCorrect = 1
           FOR XML PATH('')
           ) AS keys
        , isCorrect
        FROM @temp AS t
        GROUP BY questionID, isCorrect
        HAVING isCorrect = 1
    ) AS connected
) AS result
ORDER BY QuestionID, Answere

Upvotes: 1

Related Questions