简体   繁体   English

在不知道列名的情况下选择表的统计操作

[英]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.

相关问题 SQL Server在不知道列名的情况下从表中选择数据 - SQL Server Select data from table without knowing column names 在不知道列名的情况下组合任意表 - Combine arbitrary tables without knowing their column names SQL:在不知道所有列名的情况下,从连接中的一个表中选择所有值? - SQL: Select all values from one table in a join while not knowing all column names? 如何从表中选择具有相同但随机值的列中的行,而只通过一个查询却不知道该值? - How to select rows from a table with identical but random values in a column without knowing that value with only one query? 可以在不知道结果列名的情况下进行 SQL Server Pivot 吗? - Can SQL Server Pivot without knowing the resulting column names? 转置/数据透视表,但不知道属性的数目或名称 - Transpose/Pivot Table without knowing the number or names of attributes 选择到具有不同列名的表中 - select into a table with different column names 如何在不知道表名称的情况下选择用于SQL查询的表? - How to select table for sql query without knowing the table name? 选择选择语句的列名和表名 - Selecting column names and table names of a select statement 通过只知道没有时间的日期从表中选择 (ORACLE) - Select from table by knowing only date without time (ORACLE)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM