使用内部联接在SQL Server中选择查询问题

时间:2016-07-29 14:32:49

标签: sql sql-server sql-server-2008

在SQL Server中,我正在尝试获取必须分配以下主题的学生ID:

'English', 'Tamil', 'Maths'

我需要获得今天分配了“数学”科目的学生ID,并在任何一天分配“英语”,“泰米尔语”。

但是下面的查询检查所有主题分配日期是今天

SELECT DISTINCT 
    ca.student_id 
FROM 
    student st
INNER JOIN 
    student_subject ON student_subject.student_id = st.student_id 
INNER JOIN 
    subject ON subject.sub_id = student_subject.sub_id 
            AND student_subject_txt IN ('English', 'Tamil', 'Maths')  
            AND student_subject_assigned_Date = GETDATE()
GROUP BY
    ca.student_id 
HAVING
    COUNT(ca.student_id) = 3;

3 个答案:

答案 0 :(得分:1)

试试这个:

Select ca.student_id 
From student st
Where Exists 
   (Select * from student_subject mss
       join subject ms on ms.sub_id = mss.sub_id
    Where mss.student_id=st.student_id 
       And ms.student_subject_txt = 'Maths'
       And student_subject_assigned_Date = 
           dateAdd(day, DateDiff(day, 0, getdate()), 0))
And Exists 
   (Select * from from student_subject etss
       join subject ets on ets.sub_id = etss.sub_id
    Where etss.student_id=st.student_id 
       And ets .student_subject_txt in ('English', 'Tamil'))

注意:我将GetDate()更改为生成仅日期值而不是当前日期和时间的表达式。 GetDate()生成一个日期和时间,你不会得到任何结果 如果您使用的是SQL Server的最新版本,则可以将Getdate()强制转换为Date ...

Select ca.student_id 
From student st
Where Exists 
   (Select * from student_subject mss
       join subject ms on ms.sub_id = mss.sub_id
    Where mss.student_id=st.student_id 
       And ms.student_subject_txt = 'Maths'
       And student_subject_assigned_Date = Cast(getdate() as Date))
And Exists 
   (Select * from from student_subject etss
       join subject ets on ets.sub_id = etss.sub_id
    Where etss.student_id=st.student_id 
       And ets .student_subject_txt in ('English', 'Tamil'))

答案 1 :(得分:0)

这应该有效。请注意,您不需要distinct

SELECT      ca.student_id 
FROM        student st
INNER JOIN  student_subject 
        ON  student_subject.student_id=st.student_id 
INNER JOIN  subject 
        ON  subject.sub_id=student_subject.sub_id 
WHERE       student_subject_txt in( 'English','Tamil', 'Maths')  
        AND (
                    (student_subject_txt = 'Maths' AND student_subject_assigned_Date = CONVERT(DATE, GETDATE()))
                OR  student_subject_txt <> 'Maths'
            )
GROUP BY    ca.student_id 
HAVING      COUNT(ca.student_id)=3;

修改 @CharlesBretana是对的,您只需要比较getdate()的日期部分。编辑相应。

答案 2 :(得分:-3)

我不确定您的查询尝试的是什么,但如果您只想要计数= 3的结果,请执行此操作(我将组更改为具有):

SELECT DISTINCT ca.student_id FROM student st
    INNER JOIN student_subject ON  student_subject.student_id=st.student_id 
    INNER JOIN subject ON subject.sub_id=student_subject.sub_id 
    AND student_subject_txt in( 'English','Tamil', 'Maths')  and
    student_subject_assigned_Date = GETDATE()
    having ca.student_id =3;