我需要计算两个表中的单列。
代码片段
select
((select count(Gender) from tableA) +
(select Count(Gender) from tableB)) as Total Count
select
((select Sum(Case when Gender = M then 1 else 0) from tableA) +
(select Sum(Case when Gender = M then 1 else 0) from tableB)) as Male Count
select
((select Sum(Case when Gender = F then 1 else 0) from tableA) +
(select Sum(Case when Gender = F then 1 else 0) from tableB)) as Female Count
通过这些代码片段,我可以得到 3 个行集的结果。有没有办法在一个包含三列的单个行集中获得所有三个计数(总计数、男性计数、女性计数)?
其他场景,我需要根据不同的 if else 条件获取同一存储过程中相同列的计数。有没有办法获得这些计数,而不是为每个条件重复相同的代码?
答案 0 :(得分:1)
看来你可以尝试联合这两个表并应用聚合。
SELECT COUNT(GENDER),SUM(CASE WHEN X.GENDER='MALE' THEN 1 ELSE 0 END)AS MALE_COUNT,
SUM(CASE WHEN X.GENDER='FEMALE' THEN 1 ELSE 0 END)AS FEMALE_COUNT
FROM
(
select gender from tablea
union all
select gender from tableb
)AS X