簡體   English   中英

Select 不同表中相同條目的計數

[英]Select count of same entries in different tables

我有 3 張桌子


| ID   | Name   |
|:---- |:------:| 
| 1    | Brie   | 
| 2    | Ray    | 
| 3    | James  | 

Table2

| ID   | Q_id   | Q_no  | ans |
|:---- |:------:| -----:|----:|
| 1    | 2304.  | 1     |  A  |
| 1    | 2304.  | 2     |  A  |
| 1    | 2305.  | 1     |  C  |
| 2    | 2304.  | 2     |  A  |
| 2    | 2305.  | 1     |  C  |
| 3    | 2304.  | 1     |  A  |
| 3    | 2305.  | 2     |  D  |

Table3
 | Q_id   | Q_no  | correct_ans |
 |:------:| -----:|------------:|
 | 2304.  | 1     |  A          |
 | 2304.  | 2     |  B          |
 | 2305.  | 1     |  C          |
 | 2305.  | 2     |  D          |

我需要在表 2 中打印一個帶有 ID、名稱和計數的表,其中 ans 與表 3 中的正確答案匹配

| ID   | Name   | ans_count  |
|:---- |:------:| ----------:|
| 1    | Brie   |   2        |
| 2    | Ray    |   1        |
| 3    | James  |   2        |
Select t1.ID, Name, count(t2.ans) as ans_count
from Table1 t1
join Table2 t2 on t1.ID=t2.ID
join Table3 t3 on t2.Q_id=t3.Q_id
where t2.ans=t3.correct.ans and t2.q_no=t3.q_no
group by t1.ID
order by t1.ID

我在哪里做錯了? 抱歉,我是 SQL 的新手。

它仍然不清楚你在追求什么,但這糾正了查詢的明顯問題。

Select t1.ID, Name, count(*) as ans_count
from Table1 t1
join Table2 t2 on t1.ID=t2.ID
join Table3 t3 on t2.Q_id=t3.Q_id
where t2.ans=t3.correct.ans
group by t1.ID, t1.Name  ///<---------------
order by t1.ID

我認為您需要按 Id 和 Name 分組

您應該始終將表與所有匹配的列鏈接起來

AND GROUP By 應該包含所有沒有聚合的列 function

SELECT t1.ID,t1.`Name`,COUNT(*) as correct_answers
FROM table1 t1 
  JOIN table2 t2 ON t1.ID = t2.ID
  JOIN table3 t3 ON t2.`Q_id` = t3.`Q_id` AND  t2.`Q_no` = t3.`Q_no`
WHERE t3.`correct_ans` = t2.`ans`
GROUP BY t1.ID,t1.`Name`
order by t1.ID
ID 姓名 正確答案
1 布里干酪 2
2 射線 1
3 詹姆士 2

小提琴

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM