我有一个名为attendance
的表,其中包含roll
,class_id
,status
和att_date
列。
我有另一个名为class
的表格,其中包含class_id
列和name
列
我想选择具有class_id
number
roll
的{{1}}和status = 1
的{{1}},然后使用date="some_date"
将其连接到类表再次适用于分支="计算机科学"
但是我遇到了一些问题。 这是我的表出席的一个例子:
inner join.
这是我的表类的一个例子:
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
有人可以解释一下吗? 我该如何处理查询?
答案 0 :(得分:2)
在group by
:
group 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;
答案 1 :(得分: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