在SELECT中添加逻辑

时间:2013-05-15 20:33:24

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

请注意在下面的查询中,括号内的前两个查询,我添加了两个重复的查询,我确信这不是一个好习惯。我需要在需要值的任何时候重复此查询。

SQL Server抛出一个异常,即不在SELECT关键字中写入DECLARE。我能做什么或者我缺少什么来重构它?

SELECT A.StudentId,
(
    CASE WHEN (SELECT B.OverwrittenScore
        FROM dbo.OverwrittenScores AS B
        WHERE B.StudentId = A.StudentId 
        AND B.AssignmentId = @assignmentId
        ) IS NOT NULL
            THEN (
                SELECT B.OverwrittenScore
                FROM dbo.OverwrittenScores AS B
                WHERE B.StudentId = A.StudentId 
                AND B.AssignmentId = @assignmentId)
            ELSE (-- ANOTHER QUERY, BY THE MOMENT: SELECT 0 ) 
    END
) AS FinalScore
FROM dbo.Students AS A

2 个答案:

答案 0 :(得分:6)

我的建议是使用JOIN

SELECT A.StudentId,
    case 
        when B.OverwrittenScore is not null
        then B.OverwrittenScore
        else 0 
    end AS FinalScore
FROM dbo.Students AS A
LEFT JOIN dbo.OverwrittenScores B
    ON B.StudentId = A.StudentId 
    AND B.AssignmentId = @assignmentId

如果你想在else中使用另一个select,那么你可以根据需要添加更多的连接:

SELECT A.StudentId,
    case 
        when B.OverwrittenScore is not null
        then B.OverwrittenScore
        else c.whatever
    end AS FinalScore
FROM dbo.Students AS A
LEFT JOIN dbo.OverwrittenScores B
    ON B.StudentId = A.StudentId 
    AND B.AssignmentId = @assignmentId
LEFT JOIN anothertable c
   ON a.col = c.col

甚至可以使用COALESCE替换空值:

SELECT A.StudentId,
    coalesce(B.OverwrittenScore, 0) as FinalScore 
FROM dbo.Students AS A
LEFT JOIN dbo.OverwrittenScores B
    ON B.StudentId = A.StudentId 
    AND B.AssignmentId = @assignmentId

答案 1 :(得分:0)

不确定DECLARE的错误来自哪里,但您可以更改显示的内容

SELECT 
    A.StudentId,
    COALESCE(B.OverwrittenScore, 0) AS FinalScore
FROM dbo.Students AS A
LEFT JOIN dbo.OverwrittenScores AS B
    ON A.StudentId = B.StudentId AND B.AssignmentId = @assignmentId