我有student_uid,grade,test_name作为列的表我想计算每个等级有多少...这个
SELECT a.grade,COUNT(a.grade) AS count1
FROM 2015_2016_x_english_grades AS a
where test_name='ut1_marks'
GROUP BY grade
对于单个表,如何为多个表执行此操作
我的疑问:
SELECT a.grade, COUNT(a.grade),b.grade,COUNT(b.grade)
FROM 2015_2016_x_english_grades a
INNER JOIN 2015_2016_x_hindi_grades b ON a.grade=b.grade
WHERE a.test_name = b.ut1_marks='ut1_marks'
GROUP BY a.grade,b.grade
这有什么问题? 我也尝试过这个 SELECT a.grade,COUNT(a.grade),(SELECT COUNT(b.grade)FROM 2015_2016_x_biology_grades b其中b.test_name ='ut1_marks'GROUP BY b.grade)as count1 FROM 2015_2016_x_biology_grades a where test_name ='ut1_marks'GROUP BY一个品级 它说[Err] 1242 - 子查询返回超过1行
答案 0 :(得分:1)
在子查询中进行计数,并加入子查询。
SELECT e.grade, english_count, hindi_count
FROM (SELECT grade, COUNT(*) AS english_count
FROM 2015_2016_x_english_grades
WHERE test_name = 'ut1_marks'
GROUP BY grade) AS e
JOIN (SELECT grade, COUNT(*) as hindi_count
FROM 2015_2016_x_hindi_grades
WHERE test_name = 'ut1_marks'
GROUP BY grade) AS h
ON e.grade = h.grade
或者,如果每个表中都有唯一的密钥,您可以执行以下操作:
SELECT e.grade, COUNT(DISTINCT e.id) AS english_count, COUNT(DISTINCT h.id) AS hindi_count
FROM 2015_2016_x_english_grades AS e
JOIN 2015_2016_x_hindi_grades AS h ON e.grade = h.grade AND e.test_name = h.test_name
WHERE e.test_name = 'ut1_marks'
GROUP BY e.grade
请注意,如果两个表中都存在等级,则这两个查询都只显示等级。要获得仅存在于一个表中的成绩,您需要FULL OUTER JOIN
,但MySQL没有此操作。参见
如何模仿它们。