【问题标题】:select count inside select dinstinct在 select distinct 中选择 count
【发布时间】:2016-08-20 11:27:48
【问题描述】:

我有一个名为attendance 的表,其中包含rollclass_idstatusatt_date 列。
我有另一个名为class 的表,其中包含class_idname 列。
我想选择不同的class_id 并计算numberrollstatus = 1 where date="some_date" 然后使用inner join. 将其连接到班级表并再次应用 where branch ="Computer science"

但是我遇到了一些问题。 这是我的餐桌考勤示例:

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

谁能解释一下?
我该如何处理查询?

【问题讨论】:

    标签: mysql


    【解决方案1】:

    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;
    

    【讨论】:

    • 嘿@Gordon 我需要更多帮助。考虑如果一天中有 2 个或更多相同卷的条目(att_date 列),您的查询也会计算它们。如何在此查询中添加不同的 att_date ?
    • @TomCruise 。 . .您可以使用 attendance 的子查询,或者您应该使用合适的示例数据和所需结果提出另一个问题。
    • 你能举出考勤子查询的例子吗?
    【解决方案2】:

    我认为这是一种更简单的工作方式:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 2010-12-04
      • 2013-06-19
      • 2019-11-18
      • 2017-12-19
      • 2012-05-10
      • 1970-01-01
      相关资源
      最近更新 更多