我试图编写一个查询来获取所有表和视图的计数以及两者的总和
这是我到目前为止所拥有的:
Select
SCHEMA_NAME(schema_id) SchemaName,
type,
COUNT(*) TablesPerSchema,
COUNT(*) ViewsPerSchema,
'sum of tables and views' Total
From
Sys.objects
Where
type = 'U' or type = 'V'
Group By
SCHEMA_NAME(schema_id), type
Order By
Type, SchemaName
这有点作用,但我需要并排查看TablesPerSchema和ViewsPerSchema。现在它只在每列显示Count(*)
。
答案 0 :(得分:2)
基本上,您询问如何透视结果,以便每个类型的聚合显示为列。这可以使用PIVOT运算符完成:
select SchemaName,
ISNULL([U],0) as TablesPerSchema,
ISNULL([V],0) as ViewsPerSchema,
ISNULL([U],0) + ISNULL([V],0) As Total
From
(
select SCHEMA_NAME(schema_id) SchemaName,type,count(*) as TypeCount
from Sys.objects
Where type in ( 'U','V' )
group by SCHEMA_NAME(schema_id),type) T
PIVOT (
sum(TypeCount)
for [type] in ( [U],[V] )
) as pvt
结果如下:
SchemaName TablesPerSchema ViewsPerSchema Total
------------ --------------- -------------- -----------
dbo 46 117 163
GDS 0 3 3
IATA 3 10 13
Integration 2 4 6
Merchant 0 8 8
Portal 2 0 2
Reports 2 0 2
PIVOT
运算符实际上意味着对于类型列表中的每个类型:
`for [type] in ( [U],[V] )`
汇总sum(TypeCount)
将被计算并放置在与该类型同名的新列中,即V
和U
答案 1 :(得分:1)
use AdventureWorks2014
;with cte as
(
select
isnull(t.SchemaName, v.SchemaName) as SchemaName,
isnull(t.TablesPerSchema, 0) as TablesPerSchema,
isnull(v.ViewsPerSchema, 0) as ViewsPerSchema,
(isnull(t.TablesPerSchema, 0) + isnull(v.ViewsPerSchema, 0)) as 'Total'
from
(
Select
SCHEMA_NAME(schema_id) SchemaName,
type,
COUNT(*) TablesPerSchema
from
Sys.objects
Where
type = 'U'
Group By
SCHEMA_NAME(schema_id), type
) as t
full outer join
(
Select
SCHEMA_NAME(schema_id) SchemaName,
type,
COUNT(*) ViewsPerSchema
From
Sys.objects
Where
type = 'V'
Group By
SCHEMA_NAME(schema_id), type
) as v
on t.SchemaName = v.SchemaName
) select * from cte order by SchemaName
结果
SchemaName TablesPerSchema ViewsPerSchema Total
------------------------------- -------------- -----------
dbo 3 0 3
HumanResources 6 6 12
Person 13 2 15
Production 25 3 28
Purchasing 5 2 7
Sales 19 7 26
(6 row(s) affected)
这是逻辑
在你的问题中,你已经在select列中包含了类型,但是,对于每一行,因为你期望的视图和#表,只有一个类型列没有意义,所以我没有保留它我的答案。此外,TablesPerSchema和ViewsPerSchema仍然表明它们代表的对象类型。