这里有一些QuestionID和OptionID,每个选项都带有IsCorrect标志,我没有办法以所需的格式获得结果集(如附图所示),如果有人提出某种建议会有所帮助以最佳方式实现这一目标,在此先感谢,
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')
答案 0 :(得分:1)
我认为它在SQL Server中使用GROUP_CONCAT
函数(2012?):
我的答案是:
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
答案 1 :(得分:1)
试试这个:
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