Question

I have around 20 tables including examination records of students. I tried to figure out my question (Student ID = sID, i.e. Score 1 : s1) : StudentsTables : (student reg.data)

sID   name   surname   regDate     photo           ........
891   Mike   Jackson   01.01.2013  82342984.png    ....

TableA : (student scores)

sID   exam    s1    s2    s3    s4
891   6       0     0     0     20  > student 891 attended exam 6
891   10      30    80    100   75  > student 891 attended exam 10 

(count = 2)

TableB : (student documents , i.e. : document 1 : d1)

sID   d1      d2     d3     d4     d5     d6
891   true    false  true   true   true   true 

(count = 1)

TableC : (student messages)

mID   from    to    subject    message
1     10      891   any sub.   any message... > student 891 received messages (look "to")
1     10      891   mes2       other message... 
1     29      891   mes3       another message...

(count = 3)

TableD : (student payments)

sID   pID    amount    date   details   

(no student record in this table, count = 0)

..... and similar tables like above.

I want a result like below :

sID   name   surname   scoreCount   docCount   messageCount   paymentCount .....
891   Mike   Jackson   2            1          3              0            ...
892   Susan  Button    0            3          10             0            ...
893   Ahmad  Malisi    1            0          5              2            ...
894   any    any       4            1          0              0            ...
...
..
Was it helpful?

Solution

Have you tried this

Select sid,name,surname,
       (Select count(*) From student_scores Where Sid = S.Sid ) as scoreCount ,
       (Select count(*) From student_documents Where Sid = S.Sid ) as docCount ,
       (Select count(*) From student_messages Where to= S.Sid ) as messageCount  ,
       (Select count(*) From student_payments Where Sid = S.Sid ) as paymentCount ,
        .
        .
        .
From StudentsTables S
Where Sid=891

OTHER TIPS

Select sid,name,surname,
isnull(sscnt,0)  ,isnull(sdcnt  ,0)  ,isnull(spcnt  ,0)  ,isnull(smcnt,0)  

From StudentsTables S
join  (Select Sid,count(Sid) sscnt From student_scores group by Sid) ss
on ss.sid=s.sid
join  (Select Sid,count(Sid) sdcnt  From student_documents group by Sid) sd
on sd.sid=s.sid
join  (Select Sid,count(Sid) spcnt  From student_payments group by Sid) sp
on sp.sid=s.sid
join  (Select Sid,count(Sid) smcnt  From student_messages group by Sid) sm
on sm.sid=s.sid

this will query for all SId (s)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top