select
x1.
x2
...
x100
from mytab
我如何计算所有100列的平均值,最小值,最大值,标准偏差
输出中的I.E
column mean min max sigma
x1 1 1 1 1
x2 1 1 1 1
x3 1 1 1 1
如何做到?
答案 0 :(得分:2)
我将取消透视,然后进行聚合:
select v.colname, avg(v.val), min(v.val), max(v.val), stdev(v.val)
from t cross apply
(values ('x1', x1), ('x2', x2), . . .
) v(colname, val)
group by v.colname;
您需要列出values()
子句中的所有列。您可能会发现使用SQL查询或电子表格可以更轻松地构建它。
答案 1 :(得分:1)
-如果希望在不手动手工编码100列的情况下取消透视,一种选择是通过运行诸如以下的查询来生成查询字符串
select distinct
concat('x',number,',') as col1
from master..spt_values
where number>=1 and number<=100
这将生成如下行
col1
x1,
x10,
x100,
x11,
复制结果并将其粘贴到unpivot子句
例如。
create table t(x1 int, x2 int, x3 int)
insert into t values(1,1,1)
insert into t values(1,1,1)
insert into t values(1,1,1)
select y
,max(x) as max_x
,min(x) as min_x
,avg(x) as avg_x
from t
unpivot(x for y in (<use_values_from_query_generator>))m
group by y