我在一个SQL Server数据库中拥有数量不固定的视图,其中一列名为 "CONFIDENCE"。对于该集合中的每个视图,我想统计该列中出现不同值的频率。
我知道如何找到所有有 "CONFIDENCE "列的视图......我也知道如何计算该列中不同值出现的频率。
select c.table_schema as schema_name,
c.table_name as name
from information_schema.columns c
join information_schema.tables t
on c.table_name = t.table_name
where c.column_name = 'confidence'
and t.table_type = 'view'
我也知道如何计算单个视图的不同值... ...
select distinct confidence,
count(*) as occurrences
from schema.view_name
group by confidence
order by confidence;
但我不知道如何将这两者联系起来。我怀疑这与以下问题有关 cross apply
或 union all
但我只能找到用于联合固定数量的对象的资源。
你需要知道一个查询的答案才能写出另一个查询,你可以用一个小小的DSQL来解决这个问题。
DECLARE @SQL NVARCHAR(MAX) = ''
SELECT @SQL = @SQL + 'UNION ALL SELECT ''' + c.table_schema + '.' + c.table_name + ''' tbl, confidence, count(*) as occurrences FROM [' + c.table_schema + '].[' + c.table_name + '] GROUP BY confidence
'
FROM information_schema.columns c
JOIN information_schema.tables t ON c.table_name = t.table_name
WHERE c.column_name = 'confidence'
AND t.table_type = 'view'
SET @SQL = RIGHT(@SQL, LEN(@SQL) - 9)
EXEC sp_executesql @SQL