2017-02-03 43 views
1

我有兩個表:SQL查詢:需要解決下面的查詢邏輯

enter image description here

我要輸出象下面這樣的邏輯:

如果我輸入任何classcode然後我需要所有的問題這相關的類代碼。 我也想要一個問題,那就是這個問題的孩子問題。

也有可能單個類代碼與多個問題匹配。您可以看到類代碼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

@Amit Bisht,我是SQL新手。所以我不知道如何獲得輸出。 –

+0

從小開始,您將如何選擇給定類代碼的問題ID?然後我們可以考慮提出與問題ID相匹配的問題。 – Matt

回答

0

並主張最壞的答案,但沒有SQL編輯器來測試或編寫查詢,會感到高興,如果有人downvote它,但是這可能給一些提示關於邏輯

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