这个sql命令有什么问题?

时间:2012-09-14 19:05:14

标签: sql sql-server group-by having in-clause

我正在尝试创建查询,返回通过考试后的学生列表,至少X次失败。为了实现这一点,我写了以下查询,但我也得到以下错误:

  

IN子句中的值列表出错。无法解析查询文本。

我确信IN子句中的值列表很好,但我不明白为什么它会抱怨?! 以下是有问题的查询:

SELECT  StudentID
    FROM    tblStudents
    WHERE   (Sex = @Sex) AND (StudentID IN
                                        (SELECT StudentID
                                        FROM    tblTest
                                        WHERE   (TestID = @TestID) AND (@APass = 'true') AND (Score IN (27, 28, 29, 30)))
                                        GROUP BY StudentID, TestID
                                        HAVING   (COUNT(*) = 1))/*By this i meant find the the user who has passed the exam (finally)*/
                        AND (StudentID IN
                                        (SELECT  StudentID
                                        FROM     tblTest
                                        WHERE   (TestID = @TestID) AND (Score NOT IN (27, 28, 29, 30)))
                                        GROUP BY StudentID, TestID
                                        HAVING        (COUNT(*) >= @Times))/*And By this i meant only return students which passed the exam after x times of failing it*/

1 个答案:

答案 0 :(得分:1)

您的子查询似乎在)条款之后有太多IN - 这些条款应移至HAVING行。

SELECT  StudentID
FROM    tblStudents
WHERE   (Sex = @Sex) AND (StudentID IN
                (SELECT StudentID
                FROM    tblTest
                WHERE   (TestID = @TestID) AND (@APass = 'true') AND (Score IN (27, 28, 29, 30))
                GROUP BY StudentID, TestID
                HAVING   (COUNT(*) = 1)))/*By this i meant find the the user who has passed the exam (finally)*/
AND (StudentID IN
                (SELECT  StudentID
                FROM     tblTest
                WHERE   (TestID = @TestID) AND (Score NOT IN (27, 28, 29, 30))
                GROUP BY StudentID, TestID
                HAVING        (COUNT(*) >= @Times)))/*And By this i meant only return students which passed the exam after x times of failing it*/