将两个不同的不相关SQL查询(返回单列结果)合并为一个包含两列的查询结果

时间:2014-03-03 20:06:10

标签: sql sql-server

我有两个SQL查询。首先,我正在撤回所获得的总分,而在其他方面,我正在返回最大分数。现在我想在单个查询中将两者结合起来,以使其成为单个过程。查询如下:

第一次查询

   select SUM(MarksObtained) as MarksObtained from tbAnswers where QID IN(Select QID from tbQuestions where ExamID =2) 

第二次查询

Select SUM(Marks) as MaxMarks from tbQuestions where ExamID =2

我想要下面的内容返回:

Maxmarks | MarksObtained
------------------------
   100        50

我尝试了Union,但它返回了如下内容:

MarksObtained
-------------
100

50

3 个答案:

答案 0 :(得分:3)

好吧,由于查询不相关,您可以将它们放入select:

SELECT
   (
      select SUM(MarksObtained)  
      from tbAnswers where QID IN (
          Select QID from tbQuestions where ExamID = 2
      )
   ) as MarksObtained,
   (
       Select SUM(Marks)   
       from tbQuestions where ExamID = 2
   ) as MaxMarks

答案 1 :(得分:1)

即使有了公认的答案,但有必要提一下,正确的做法是使用单独的查询,因为它们只是在客户端上使用MARS,以防性能成为问题。

更新:这就是你如何组合几个查询并一起阅读它们:

using(var conn = SqlConnection(...)) {
   conn.Open();
   var cmd = conn.CreateCommand()
   cmd.CommandText = 
    @"Select SUM(MarksObtained) as MarksObtained 
      from tbAnswers 
      where QID IN(Select QID from tbQuestions where ExamID =2);"
  + @"Select SUM(Marks) as MaxMarks 
      from tbQuestions 
      where ExamID =2";

   using (var dr = cmd.ExecuteReader) {
        ... // read MarksObtained
        dr.NextResult()
        ... // readMaxMarks
        dr.Close()
   }
   conn.Close()
}

MSDN IDataReader.NextResult

答案 2 :(得分:0)

    ;WITH    CTE1 ( MarksObtained )
              AS ( SELECT   SUM(MarksObtained) AS MarksObtained
                   FROM     tbAnswers
                   WHERE    QID IN ( SELECT QID
                                     FROM   tbQuestions
                                     WHERE  ExamID = 2 )
                 ),
            CTE2 ( MaxMarks )
              AS ( SELECT   SUM(Marks) AS MaxMarks
                   FROM     tbQuestions
                   WHERE    ExamID = 2
                 )
        SELECT  MaxMarks,MarksObtained
        FROM    CTE1 ,
                CTE2