2015-04-29 82 views
0

我有兩個表abbabb_click組和計數返回SQL

abb包含哪些對象的信息ident這是活動的。 abb_click包含來自每個student_id的信息,關於每個ident

我 「只是」 想算活躍的identabb_click特定student_id數據。下面

的選擇似乎只計算活動IDENT S,不採取任何擔憂,如果IDENTabb_click

你可以在這裏看到小提琴:http://sqlfiddle.com/#!9/b7262/1


結果應該是: 爲student_id數據945 - 2的活性的ident小號

問題:我該怎麼辦「調整「SELECT來計算有效ident s在表abb加入abb_click


SELECT t.student_id, number_of_idents 
FROM `abb_click` AS t 
    INNER JOIN 
     (SELECT ident, COUNT(ident) as number_of_idents FROM `abb` AS k 
     WHERE k.active = '1' 
    ) AS t3 
    ON t.ident = t3.ident 
WHERE t.student_id = '945' 
GROUP BY t.student_id 
ORDER BY number_of_idents ASC; 

abb

bid, ident, active 

abb_click

kid, ident, student_id, click 

數據表abb

1, 'ma53', 1 
2, 'ma664', 1 
3, 'ma779', 0 
4, 'ma919', 1 

數據表abb_click

1, 'ma53', 945, 'E' 
2, 'ma53', 945, 'E' 
3, 'ma53', 945, 'C' 
4, 'ma664', 945, 'C' 
5, 'ma664', 945, 'A' 
6, 'ma664', 945, 'E' 
7, 'ma779', 945, 'A' 

回答

1

我相信這應該做你想做的。

select student_id, COUNT(distinct ac.ident) as active_idents 
from abb_click ac 
join abb on abb.ident = ac.ident 
where abb.active = 1 
--and student_id = 945 
group by student_id 
+0

非常整齊,工作得很好(額外的'和student_id = 945')。非常感謝您的時間和幫助。謝謝@Sander! – Per76

1

除非我已經錯過,瞭解這應該工作。

SELECT abb.*, COUNT(abb_click.id) as total_abb_clicks 
FROM abb 
INNER JOIN abb_click ON abb_click.ident = abb.ident 
WHERE abb.active = 1 && abb_click.student_id = 945 
GROUP BY abb.id 

- 編輯:抱歉,我忘記了學生的狀況。因此,這應該返回:

投標,IDENT,活躍,total_abb_clicks
1, 'ma53',1,3
2, 'ma664',1,3
4, 'ma919',1,1

+1

謝謝@Camway。不是我想要的結果,但確實非常有用。 – Per76

+2

現在看到答案,我看到你來自哪裏;我想念明白。 – Camway

1

可以返回的ident的獨特價值,並通過將它們分組,然後用abb加入和做計數student_id數據:

SELECT click.student_id, COUNT(click.ident) as total_abb_clicks 
FROM abb 
INNER JOIN (select ident, student_id from abb_click group by ident, student_id) click ON click.ident = abb.ident 
WHERE abb.active = 1 and click.student_id=945 
GROUP BY click.student_id 
+1

這工作得很好。非常感謝您的時間和幫助。謝謝@Sami Kuhmonen! – Per76