我有一个声明计算有attr3 = 1
的记录数。
SELECT 'Dept' AS table_name, COUNT(*)
FROM ((select attr3 from table1) union all
(select attr3 from table2)
) t
WHERE attr3 = '1';
现在我需要另一个声明做同样事情的声明,但要计算有attr3 = 2
的记录数。
SELECT 'Dept' AS table_name, COUNT(*)
FROM ((select attr3 from table1) union all
(select attr3 from table2)
) t2
WHERE attr3 = '2';
理想情况下,数据将以此格式显示
Dept count(*)
attr3 = 1 4
attr3 = 2 6
如果我单独执行语句,此方法有效,我只是想将它们连接在一起。有人可以帮忙吗?
答案 0 :(得分:2)
简单的GROUP BY
和WHERE attr3 in()
就足够了。
SELECT Z.attr3 as Dept, count(*) as cnt
FROM (SELECT attr3 FROM table1
UNION ALL
SELECT attr3 FROM table2) Z
WHERE attr3 in ('1','2')
GROUP BY Z.attr3
由于attr3定义了您想要计数的组,因此只需将其分组并通过where子句将结果限制为1,2之后的结果。
答案 1 :(得分:0)
小组将完成这项工作。
SELECT 'Dept' AS table_name, COUNT(*)
FROM ((select attr3 from table1) union all
(select attr3 from table2)
) t2
WHERE attr3 = '2'
group by dept;