简体   繁体   English

选择内部选择计数

[英]select count inside select dinstinct

I have a table named attendance which has columns roll , class_id , status and att_date . 我有一个表命名为attendance其具有柱rollclass_idstatusatt_date
I have another table named class which has columns class_id and name . 我还有一个名为class表,该表具有class_idname列。
I want to select distinct class_id and count number of roll which has status = 1 where date="some_date" and then connect it to class table using inner join. 我想选择不同的class_id并计数status = 1roll number ,其中date="some_date" ,然后使用inner join.联接将其连接到类表inner join. and again apply where branch ="Computer science" 并再次应用分支=“计算机科学”

But I'm facing some problem. 但是我面临一些问题。 This is an example of my table attendance: 这是我的表出席情况的一个示例:

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

This is an example of my table class: 这是我的表类的一个示例:

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

and I want something like this : 我想要这样的东西:

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

Can someone explain me ? 有人可以向我解释吗?
How can I approach with the query ? 如何处理查询?

Use a group by within a group by : 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;

EDIT: 编辑:

Note: This aggregates by cnt , and you might not want to do that (your results are ambiguous). 注意:这是通过cnt聚合的,您可能不想这样做(您的结果不明确)。 This might be sufficient: 这可能就足够了:

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;

Or even: 甚至:

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

I think this is a more simpler way to do the job: 我认为这是一种更简单的工作方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM