sql server—组合两个包含联接的select sql查询的结果

bqjvbblv  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(415)

我需要结合这两个sql查询来查找给定模式中空表和非空表的总数。
下面的查询生成两个结果输出-这是正确的。
但是,如何将这些select语句中的两个连接在一起,作为一个具有两个结果输出的查询语句呢?
我试过使用union,union all,intersect all,它不会给我想要的结果。

--- query for Empty tables: 
select count (*) from 
(
select schema_name(tab.schema_id) + '.' + tab.name as [emptytable]
   from sys.tables tab
        inner join sys.partitions part
            on tab.object_id = part.object_id
where part.index_id IN (1, 0) -- 0 - table without PK, 1 table with PK
group by schema_name(tab.schema_id) + '.' + tab.name
having sum(part.rows) = 0 
) as subquery;
--- query for Non-Empty tables: 
select count (*) from 
(
select schema_name(tab.schema_id) + '.' + tab.name as [non_emptyTable]
   from sys.tables tab
        inner join sys.partitions part
            on tab.object_id = part.object_id
where part.index_id IN (1, 0) -- 0 - table without PK, 1 table with PK
group by schema_name(tab.schema_id) + '.' + tab.name
having sum(part.rows) > 0 
) as subquery;
k5ifujac

k5ifujac1#

使用条件聚合:

select sum(case when size = 0 then 1 else 0 end) as num_empty,
       sum(case when size > 0 then 1 else 0 end) as num_nonempty
from (select schema_name(tab.schema_id) + '.' + tab.name as table_name,
             sum(part.rows) as size
      from sys.tables tab join
           sys.partitions part
           on tab.object_id = part.object_id
      where part.index_id in (1, 0) -- 0 - table without PK, 1 table with PK
      group by schema_name(tab.schema_id) + '.' + tab.name
     ) t

相关问题