2016-08-20 57 views
1

我有一个名为attendance的表,它有roll,class_id,0 statusatt_date列。
我有另一个表名为class其中有列class_idname
我要选择不同的class_id和计数的roll具有status = 1其中date="some_date"number,然后使用inner join.它连接到类表,然后再次申请,其中分支=“计算机科学”select select select dinstinct

但我面临着一些问题。 这是我的表出席一个例子:

roll | class_id | status | att_date 
abc | 1  | 0 | 19-06-2016 
cvb | 2  | 1 | 19-06-2016 
nbs | 1  | 1 | 19-06-2016 
lkl | 3  | 1 | 19-06-2016 
ewq | 3  | 1 | 19-06-2016 
dff | 2  | 1 | 19-06-2016 
xyz | 2  | 1 | 19-06-2016 

这是我的表类的一个示例:

id | name | branch 
1 | CS4 | Computer Science 
2 | CS5 | Computer Science 
3 | CS6 | Mechanical 

,我想是这样的:

total number of roll with status 1 | class_id | name 
1         | 1  | CS4 
3         | 2  | CS5 
2         | 3  | CS6 

有人能解释我 ?
我该如何处理查询?

回答

2

使用group bygroup by

select cnt, count(*) as num_status_1, 
     group_concat(a.class_id order by a.class_id) as class_ids, 
     group_concat(c.name order by a.class_id) as class_names 
from (select class_id, count(*) as cnt 
     from attendance 
     where status = 1 
     group by class_id 
    ) a join 
    class c 
    on a.class_id = c.class_id 
group by cnt; 

编辑:

注:此聚集由cnt,你可能不希望这样做,(你的结果是不明确的)。这可能是不够的:

select cnt, 
     a.class_id, c.nameclass_names 
from (select class_id, count(*) as cnt 
     from attendance 
     where status = 1 
     group by class_id 
    ) a join 
    class c 
    on a.class_id = c.id; 

甚至:

select c.*, 
     (select count(*) from attendance a where a.status = 1 and a.class_id = c.id) 
from class c; 
+0

它给错误,a.name未知领域 –

+1

没关系,我得到了我的答案。谢谢 ! –

+0

嘿@戈登我需要一个更多的帮助。考虑如果一天中有两次或两次以上同一次滚动输入(att_date列),那么您的查询也会对它们进行计数。如何在此查询中添加不同的att_date? –

0

我觉得这是一个比较简单的做的工作方式:

select a.class_id, b.name, count(a.*) as tot_status_1 
    from attendance a, class b 
    where a.class_id=b.id and a.status=1