SQL查询:需要解析下面的查询逻辑

时间:2017-02-03 06:00:25

标签: sql sql-server-2012

我有两张桌子:

enter image description here

我想输出如下逻辑:

如果我输入任何类代码,那么我需要提出与该类代码相关的所有问题。 我还想问一个问题,那就是那个问题的孩子问题。

单个类代码也可能与多个问题匹配。你可以看到类代码65005。在这种情况下,我们考虑上层父问题。

如果我将通过42908,那么我的输出如下:

enter image description here

如果您有任何疑问,请与我们联系。

   SELECT * FROM QuestionMaster as a INNER JOIN [ClassCodeQuestionMapping] as b ON a.QuestionId = b.QuestionId 
    WHERE b.ClassCode=42908

我尝试了以上查询,但我无法解决孩子的问题。

感谢。

1 个答案:

答案 0 :(得分:0)

提出一个最差的答案,但没有sql编辑器来测试或编写查询,如果有人对它进行了投票,会感到高兴,但这可能会给出一些关于逻辑的暗示

Select c.Question From (SELECT a.Question, a.ParentQuestionId
FROM QuestoinTable as a
INNER JOIN QuestoinClassMappingTable as b
ON a.QuestionId = b.QuestionId 
where b.ClassCode = 1234) as c 
INNER JOIN QuestoinTable as d
ON c.ParentQuestionId= d.QuestionId
UNION
Select d.Question From (SELECT a.Question, a.ParentQuestionId
FROM QuestoinTable as a
INNER JOIN QuestoinClassMappingTable as b
ON a.QuestionId = b.QuestionId 
where b.ClassCode = 1234) as c 
INNER JOIN QuestoinTable as d
ON c.ParentQuestionId= d.QuestionId
相关问题