[英]Select statistical operations on table without knowing column names
I am analyzing the data quality of a number of tables in regards to quantitative measures like Min, Max, Average, Standard Deviation etc. 我正在分析定量,最小,最大,平均值,标准偏差等定量表的数据质量。
How do I select different statistical operations (Min, Max, Standard Deviation...) on all table columns without knowing the table column names ? 在不知道表列名称的情况下,如何在所有表列上选择不同的统计运算(最小,最大,标准偏差...)?
So something like: 所以像这样:
Select min(col1), max(col1), stdev(col1), min(col2)... , min(colN) from table1
从表1中选择min(col1),max(col1),stdev(col1),min(col2)...,min(colN)
But making a dynamic reference to the column names because I have to run this on numerous tables with different column names and I dont want to change code every time. 但是要动态引用列名,因为我必须在具有不同列名的许多表上运行它,并且我不想每次都更改代码。
I am using SQL Management Studio. 我正在使用SQL Management Studio。
Thank you very mcuh 非常感谢您
Well, here is one fairly reasonable way to do such a thing: 好吧,这是做这种事情的一种相当合理的方法:
Note You need to add the rest of the numeric data types to this example. 注意您需要将其余的数字数据类型添加到此示例。
DECLARE @SQL nvarchar(max) = '';
SELECT @SQL = @SQL +
'
UNION ALL
SELECT '''+ TABLE_NAME +''' As TableName,
'''+ COLUMN_NAME +''' As ColumnName,
MIN('+ COLUMN_NAME +') As [Min],
MAX('+ COLUMN_NAME +') As [Max],
STDEV('+ COLUMN_NAME +') As [STDEV]
FROM '+ TABLE_NAME
FROM information_schema.columns
WHERE DATA_TYPE IN('tinyint', 'smallint', 'int', 'bigint') -- Add other numeric data types
SELECT @SQL = STUFF(@SQL, 1, 11, '') -- Remove the first `UNION ALL` from the query
EXEC(@SQL)
The result of this query will be structured like this: 查询结果的结构如下:
TableName ColumnName Min Max STDEV
Table1 Col1 -123 543 100
Table1 Col2 54 72 5
Table1 Col3 0 1000 100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.