[英]Combine two different unrelated SQL queries( returning single column results) into one query result with two columns
I have two sql queries. 我有两个SQL查询。 In first I am returing total marks obtained and in other i am returning maximum marks .
首先,我重述获得的总分数,而在其他方面,我则归还最大分数。 Now i want to combine both in single query for the purpose of making it into single procedure.
现在,我想将两者合并在单个查询中,以使其成为单个过程。 Queries are as :
查询如下:
First Query 第一次查询
select SUM(MarksObtained) as MarksObtained from tbAnswers where QID IN(Select QID from tbQuestions where ExamID =2)
2nd Query 第二查询
Select SUM(Marks) as MaxMarks from tbQuestions where ExamID =2
I want something like below to return: 我想要下面的内容返回:
Maxmarks | MarksObtained
------------------------
100 50
I tried Union, but it returned something like below: 我尝试了Union,但是返回了如下内容:
MarksObtained
-------------
100
50
Well, since the queries are unrelated, you can just throw them into the 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
Even with accepted answer it is make sense to mention that probably the right thing to do is to use separate queries, as they are and just use MARS on the client, in case performance was an issue. 即使有可接受的答案,也有必要提一下,也许正确的做法是使用单独的查询,并按原样使用,并在客户端上使用MARS,以防出现性能问题。
UPDATE: Thats how you can combine several queries and read them all together: 更新:这样就可以组合多个查询并将它们全部读取:
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 MSDN IDataReader.NextResult
;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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.