2012-12-01 144 views
0

我有兩個表。嵌套sql查詢找到計數

  1. 學生表的數據爲rollno,batchids。
  2. 批處理表,批處理,courseid。

學生表的batchids列包含逗號分隔的各種課程的學生可能在被登記batchids。現在,我希望得到學生的數量coursewise。有人能幫我嗎?

到目前爲止,我已經達到

select * 
from students 
where batchids in (select id from batches where courseid=1) 

這給我的學生在過程中與ID列表「1」。

+3

學生表中逗號分隔的batchids列表,這使複雜的事情變得複雜。 courseid = 1的相關性是什麼? – Brettski

+1

您正在使用哪種RDBMS - SQLServer,MySQL ....? – codingbiz

+0

在繼續之前,您應該修復您的數據模型。 「*逗號分隔列表*」是一個非常糟糕的主意。 –

回答

0

使用count()。

Select count(*) 
from students 
where batchids in (select id from batches where courseid=1) 
0

如果我正確理解你的數據,你有這樣的:

學生:(S1, '1,2,3')

batchids:( '1,2,3' ,1),('1,2,3',2),'1,2,3',3)

假設這是正確的,逗號分隔列表只是進入batchids表的一個鍵。因此,要獲得每個課程的計數,請執行以下操作:

select courseid, count(*) 
from batches b join 
    students s 
    on b.studentid = s.studentid 
group by courseid