2016-08-20 49 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