我有两张桌子
表1
Name marks John 50 Smith 70 Adam 60 Roy 70
表2
Score Grade other 50 C 1.5 60 B 0.7 70 A 0.8 70 A 1.0
我想知道有多少人获得A,B,C通行证 我希望得到一个输出
Grade Count C 1 B 1 A 2
我试过的查询是
SELECT table2.Grade,
COUNT(DISTINCT table2.Grade) as count
FROM table1
LEFT JOIN table2
ON table1.Mark = table2.Score
GROUP BY table2.Grade;
但是它给了
Grade Count C 1 B 1 A 4
那么如何删除重复项呢? 请帮忙。
答案 0 :(得分:1)
在第二张表中,您有重复的行:
Score Grade other
50 C 1.5
60 B 0.7
70 A 0.8
70 A 1.0
在这里,有A' s,当你根据字段" Grade - Score"与第一张表联系时,整个联接是:
Jhon 50 C
Smith 70 A
Smith 70 A --> Second A from second table
Adam 60 B
Roy 70 A
Roy 70 A --> Second A from second table
因此,分组依据和计数将在此处获得4个字段等级:
A 4 --> 2 Smith and 2 Roy
B 1
C 1
所以,了解每个年级有多少人:
select tb2.Grade GradeMark, count(*) TotalPersons
from table1 as tb1
left join (select tbi2.Score, distinct(tbi2.Grade), tbi2.other, from table2 tbi2) as tb2 on tb2.Grade = tb1.marks
group by tb2.Grade
此查询将从table2中选择不同的值,与表1连接并计算每个年级的结果,因此您应该得到:
A 2
B 1
C 1
答案 1 :(得分:0)
您不需要JOIN
。您可以使用简单的group by
尝试使用count()
select Grade, count(*) as `Count`
from table2
group by Grade;