(SQL)查询的任何想法?

时间:2016-04-19 12:48:15

标签: sql sql-server database sql-server-2014

社区,
所以我有一个包含几个表的数据库,应该以我现在无法想象的方式加入它们。我的SQL技能非常基础,所以也没有帮助我。

但现在的情况如下:

我有一个表问题和一个表答案

每个问题都有一个ID和一个文本以及4个答案,这些答案位于答案表中。在答案 - 列“正确”中有真或假(是假还是真答案)

Tables

现在,棘手的部分是,我还有2个表,名为团队 TAnswers 。如果用户回答问题,他的选择将进入 TAnswers -table。

enter image description here

所以SELECT * FROM TAnswers给了我这个:

enter image description here

最后,要生成一个Result-table,我希望它看起来像这样:

TEAM | CORRECT ANSWERS

任何人都可以帮助我吗?抱歉我的写作最终不好,我的咖啡有点太多了:))

修改

所以经过一些尝试并阅读Reddit教程(感谢Rich Brenner)后,我自己找到了答案(其他的很好,但不是我搜索过的)。所以这是我的答案:

SELECT Team, COUNT(a.TeamID) as [Correct Answers] FROM TAnswers as a
RIGHT JOIN Answers ON a.AnswerID = Answers.ID
RIGHT JOIN Teams ON a.TeamID = Teams.IDTeam
WHERE Correct = 1
GROUP BY Team
ORDER BY [Correct Answers] desc;

5 个答案:

答案 0 :(得分:2)

这样的事情:

select (select team from Teams where teamid = t.teamid) as team,
       count(1) 
from Questions q
   join Answers a on q.id = a.questionId
   join TAnswers ta on ta.answerId = a.id
   join Teams t on t.id = ta.teamId
where a.correct = true
group by t.teamid;

答案 1 :(得分:1)

select t.*, a.* from Teams t, Answers a, Questions q, TAnswers ta
where ta.AnswerID = A.Id
and a.Correct = true
and ta.TeamID = t.ID

答案 2 :(得分:1)

好的,我会在这里帮助你。这似乎是一个家庭作业问题,所以我不会给你答案,而是我会帮你自己去那里。

您的基准表将是' TAnswers'因为它有连接到其他表的键。然后,您希望将左连接完成到其他表。

SELECT
a.Team
,d.Field
FROM TAnswers a
LEFT JOIN SecondTable b on a.Field = b.Field
LEFT JOIN ThirdTable c on a.Field = c.Field
LEFT JOIN FourthTable d on a.Field = d.Field

您必须处理您将要用于连接的字段。

然后,您需要弄清楚如何计算正确答案,是否要使用SUM或WHERE子句?由你决定。

答案 3 :(得分:1)

<script type="text/javascript" src="js/bootstrap.min.js"></script>

<script>
$(document).bind('mobileinit',function(){
    $.mobile.pushStateEnabled = false;
});
</script> 

<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>jQuery.noConflict(true);</script>

答案 4 :(得分:1)

SELECT
    t.Team,a.AText
FROM Teams AS t
LEFT JOIN TAnswers AS ta ON ta.TeamID=t.TeamID
LEFT JOIN Answers AS a ON a.ID=ta.AnswerID
   AND a.Correct=1

为了计算:

SELECT
    t.Team,Count(a.AText) AS [Correct Answers]
FROM Teams AS t
LEFT JOIN TAnswers AS ta ON ta.TeamID=t.TeamID
LEFT JOIN Answers AS a ON a.ID=ta.AnswerID
   AND a.Correct=1
GROUP BY t.Team