1

我有两张桌子,

学生:

rollno  | name 
1       | Abc
2       | efg
3       | hij
4       | klm

出席:

name | date       |status
Abc  | 10-10-2013 | A
efg  | 10-10-2013 | A
Abc  | 11-10-2013 | A
hij  | 25-10-2013 | A

我需要的输出是:

一些查询条件为“'10-09-2013'和'13-10-2013'之间的日期”

rollno| name |count
1     | Abc  | 2
2     | efg  | 1
3     | hij  | 0
4     | klm  | 0

我尝试使用:

SELECT p.rollno,p.name,case when s.statuss='A' then COUNT(p.rollno) else '0' end as count 
from    attendance s 
        right outer join student p 
            on s.rollno=p.rollno 
where   s.date between '10-09-2013' and '13-10-2013' 
group by p.rollno,p.regno,p.name,s.statuss 
order by p.rollno

输出是:

rollno| name |count
1   | Abc  | 2
2   | efg  | 1

我希望还附加学生表中的剩余值。我尝试了许多不同的查询,但都没有成功。是否有一个查询会返回上面所需的输出?

4

1 回答 1

2

您需要将条件从 where 移动到 join:

SELECT p.rollno,p.name,case when s.statuss='A' then COUNT(p.rollno) else 0 end as count 
from    attendance s 
        right outer join student p 
            on s.rollno=p.rollno 
            and s.date between '10-09-2013' and '13-10-2013' 
group by p.rollno,p.regno,p.name,s.statuss 
order by p.rollno;

目前,即使您有外连接,通过在 where 子句中引用外部表,您也可以有效地将其转换为内连接。attendance在, s.Datewill beNULL和 because NULLis not between的地方没有匹配'10-09-2013' and '13-10-2013'的行之间被排除。

从这个问题中看不出来,但我想你真正要找的是这个。看来您只是在对学生的状态=“A”的出席人数进行计数之后:

SELECT  p.rollno,
        p.name,
        COUNT(s.statuss) as count 
from    attendance s 
        right outer join student p 
            on s.rollno=p.rollno 
            and s.date between '10-09-2013' and '13-10-2013' 
            AND s.statuss = 'A'
group by p.rollno,p.regno,p.name,
order by p.rollno;

我已经从 group by 中删除了 s.statuss,并更改了计数,以便每个学生只有一行,而不是每个学生的每个状态一行。我已将计数中的列更改为考勤状态表中的列,以确保在没有考勤条目时获得计数为0。如果您在学生中使用一列,即使没有条目,您也会得到 1 的计数。最后,因为你只对条目感兴趣statuss = 'A'因此我也将其移至连接条件。

最后一点,建议在使用字符串作为日期时使用文化不敏感格式yyyyMMdd,因为这是完全明确的,20130201' is always the 1st February, and never 2nd January, whereas in your query10-09-2013' 可能是 9 月 10 日或 10 月 9 日,具体取决于您的设置。

于 2013-09-30T15:49:27.660 回答