获取两个选择计数语句的总和

时间:2014-12-08 04:09:23

标签: sql-server

我需要将两个选择查询合并为一个结果。

/*  Count of all classes students have passed   */
/* A */
SELECT COUNT(TECH_ID) as Number1, ct.SUBJ, ct.COU_NBR
FROM [ISRS].[ST_COU] st
JOIN [ISRS].[CT_COU_SQL] ct
ON st.COU_ID = ct.COU_ID
WHERE GRADE = 'A' OR Grade = 'B' or Grade = 'C'
GROUP BY ct.SUBJ, ct.COU_NBR

/* Total Count of all students who needed to take a course */
/* B */
SELECT COUNT(TECH_ID) as Number2, ec.SUBJ, ec.COU_NBR
FROM [dbo].[ST_MAJOR_COMMENT] st JOIN [dbo].[Emphasis_Class] ec
ON st.MAJOR = ec.Emphasis
GROUP BY ec.SUBJ, ec.COU_NBR

我需要SUBJ,COU_NBR,sum(B - A)

2 个答案:

答案 0 :(得分:1)

您可以在ctes中进行SQL查询,然后进行连接并group by

with cte1
as
(
  first query
)
, cte2
as
(
  second query
)
select cte1.subj, cte1.cou_nbr, sum(cte2.number2 - cte1.number1) as difference
from cte1
join cte2
on cte1.subj = cte2.subj
and cte1.cou_nbr = cte2.cou_nbr
group by cte1.subj, cte1.cou_nbr

答案 1 :(得分:1)

使用union:

select sum(Number1) from (
   SELECT COUNT(TECH_ID) as Number1
   -- onit all other columns from select then rest of query 1
   UNION
   -- just the count column selected then rest of query 2
) x

此语法适用于大多数数据库。