0

我在一个数组中有一组大约 9000 个导师 ID,我将它们放在一个字符串中,例如:

(1,2, 3, 4,5,6,7,....9000,9001,9002)

这样我就可以在以下查询中使用它们:

select count(student_assignment.assignment_id) as total_assignment from 
student_assignment, assigned_tutor_fk where  assignment_status = 'closed'
 and assigned_tutor_fk in (1,2, 3, 4,5,6,7,..100,101,103...9000,9001,9002)
 group by assigned tutor_fk.

我想计算与每个导师(assigned_tutor_fk)关联的总行数,以及那些没有作业的导师,即那些在表中没有作业记录的导师,我想将他们的作业计数显示为 0,我只想我的查询返回计数和assigned_tutor_fk 我的表结构是:

    assignment_id | assigned_tutor_fk | assignment_date | student_id |
    |    1        |   2               |  22-01-2011     |  4         |
    |    2        |   3               |  14-03-2011     |  5         |

我试图让我的输出是这样的:

    |total_assignment | assigned_tutor_fk |
    |      5          | 4                 |
    |      2          | 7                 |
    |      0          | 8                 |

更新:我认为我无法正确表达自己,我已经有一个根据另一个标准过滤的导师列表,将这两个查询结合起来非常复杂,所以现在我有一组导师 ID,我想要总和如果导师没有作业记录,则显示为零。请帮助我,因为我现在不知道该怎么做

4

3 回答 3

2
SELECT  t.id, COUNT(sa.assignment_id)
FROM    tutor t
LEFT JOIN
        student_assignement sa
ON      sa.assignment_tutor_fk = t.id
WHERE   t.id IN (1, 2, ..., 9002)
GROUP BY
        t.id
于 2013-01-15T12:22:23.170 回答
0
SELECT 
  count(*) as total_assignment,
  assigned_tutor_fk  
FROM assignmentTable 
GROUP BY assigned_tutor_fk 
于 2013-01-15T12:18:45.913 回答
0

不要把导师串起来。从表中选择它们并与分配和 FK 表进行 LEFT JOIN。在不知道所有表格的情况下,我猜它看起来像这样:

select 
   t.tutorId,
   count(sa.assignment_id) as total_assignment
from 
   tutor t
LEFT JOIN
   assigned_tutor_fk fk
ON
   fk.assigned_tutor_fk = tutor.tutorId 
LEFT JOIN
   student_assignment sa
ON
  fk.assignment_id = sa.id
where  
   sa.assignment_status = 'closed' OR
   ISNULL(sa.assignment_status) -- if join fails.
group by 
   t.tutorId

Left Join从导师表中检索您的所有值并将其与连接表合并(如果有匹配项)。如果不是,则插入 NULL。

于 2013-01-15T12:26:59.257 回答