返回多个SQL表的行计数列表

时间:2013-08-23 14:29:29

标签: sql export xls

希望这会很快回答。我是SQL的新手,所以我很挣扎,我可能会遗漏一些明显的东西。我有以下查询,它返回单独结果中的行计数,但我想将结果导入XLS。实现这个目标的最佳方法是什么?

select count(*) as "table_1" FROM table_1
select count(*) as "table_2" FROM table_2
select count(*) as "table_3" FROM table_3
select count(*) as "table_4" FROM table_4
select count(*) as "table_5" FROM table_5
select count(*) as "table_6" FROM table_6
select count(*) as "table_7" FROM table_7
select count(*) as "table_8" FROM table_8
select count(*) as "table_9" FROM table_9
select count(*) as "table_10" FROM table_10

非常感谢!

感谢您的帮助,这就是我与我一起提供的所需内容。

我知道这将是相当简单的事情!

SELECT 'table_1' as "Table", count (*) as "Count" FROM table_1 union all
SELECT 'table_2' as "Table", count (*) as "Count" FROM table_2 union all
SELECT 'table_3' as "Table", count (*) as "Count" FROM table_3 union all
SELECT 'table_4' as "Table", count (*) as "Count" FROM table_4 union all
SELECT 'table_5' as "Table", count (*) as "Count" FROM table_5 union all
SELECT 'table_6' as "Table", count (*) as "Count" FROM table_6 union all
SELECT 'table_7' as "Table", count (*) as "Count" FROM table_7 union all
SELECT 'table_8' as "Table", count (*) as "Count" FROM table_8 union all
SELECT 'table_9' as "Table", count (*) as "Count" FROM table_9 union all
SELECT 'table_10' as "Table", count (*) as "Count" FROM table_10

1 个答案:

答案 0 :(得分:1)

有两种方法可以做到这一点,使用union语句和带有select语句的子查询

Union会将所有结果合并到一个包含多行

的表中
select count(*) , 'Table1' as tablename FROM table_1
union all
select count(*), 'Table2' as tablename  FROM table_2
union all
select count(*) ,'Table3' as tablename FROM table_3
.....
.....

子查询将返回一行包含多列

SELECT 
   (SELECT COUNT(*) FROM table_1) as 'Table1',
   (SELECT COUNT(*) FROM table_2) as 'Table2',
   (SELECT COUNT(*) FROM table_3) as 'Table3'
 ......
 ......