admin

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

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'

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


阅读 223

收藏
2021-07-01

共1个答案

admin

试试这个:

   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'
2021-07-01