我需要帮助从两个查询中减去结果

时间:2011-07-11 09:59:52

标签: asp.net sql

    DECLARE @TotalQuestions int;
DECLARE @CorrectQuestions int;
DECLARE @IncorrectQuestions int;

SELECT (
  SET CorrectQuestion = SELECT COUNT( WiningComment)
    FROM Threads
    WHERE WiningComment IN (SELECT CommentsID
    FROM Comments
    WHERE  UsersID=@UserID)
) as 'WinningAnswers',
(
    SET TotalQuestions =  SELECT COUNT(CommentsID)
    FROM  Comments
    WHERE  UsersID=@UserID
) as 'TotalAnswers'
(
  SELECT  (TotalQuestions-CorrectQuestions ) //I am not sure about this part!!
) as 'IncorrectQuestions' 

我不确定最后一部分,我想从另一个子查询的结果中减去一个子查询的结果

1 个答案:

答案 0 :(得分:2)

试试这个:

   DECLARE @TotalQuestions int;
DECLARE @CorrectQuestions int;
DECLARE @IncorrectQuestions int;

SELECT @CorrectQuestions = COUNT( WiningComment) 
    FROM Threads
    WHERE WiningComment IN (SELECT CommentsID
    FROM Comments
    WHERE  UsersID=@UserID)


    SELECT @TotalQuestions =  COUNT(CommentsID)
    FROM  Comments
    WHERE  UsersID=@UserID


  SELECT  @IncorrectQuestions = (@TotalQuestions-@CorrectQuestions ) 

Select @CorrectQuestions as 'WinningAnswers',
@TotalQuestions as 'TotalAnswers',
@IncorrectQuestions as 'IncorrectQuestions'