如何获得分组的列按值计数

时间:2019-11-15 09:32:50

标签: mysql sql

你好,我有一个表格,其中一列是jtypeid(14是活动| 12是考试)和Studentid

我想获得活动计数和考试计数作为列。我的查询是

SELECT name,surname, count(jtypeid) as activity 
FROM lms_journal INNER JOIN 
     lms_student 
     ON lms_student.id = lms_journal.studentid 
WHERE lms_journal.jtypeid=14 
GROUP BY studentid 
UNION 
SELECT name,surname, count(jtypeid) as exam 
FROM lms_journal INNER JOIN 
     lms_student 
     ON lms_student.id = lms_journal.studentid 
WHERE lms_journal.jtypeid=12 
GROUP BY studentid

例如

id jtypeid studentid
1    14       100
2    14       101
3    12       100
4    12       101
5    14       102
6    14       100

结果应为:

studentid exam activity
100       1       2
101       1       1
102       0       1

2 个答案:

答案 0 :(得分:3)

您可以使用条件聚合:

select 
    studentid,
    sum(jtypeid = 12) exam,
    sum(jtypeid = 14) activity
from lms_journal
group by studentid

表达式sum(jtypeid = <n>)充分利用了以下事实:在MySQL中,在数字上下文中将真实条件评估为1,而将错误条件评估为0。这使查询更短,并且以某种方式更具可读性(如果您知道窍门)。

答案 1 :(得分:2)

您可以尝试条件聚合

select studentid, 
       count(case when jtypeid=12 then 1 end) as exam,
       count(case when jtypeid=14 then 1 end) as activity
from tablename
group by studentid