我有一张这样的表
col_1 col_2 ... col_n
1 2 ... 3
2 -2 ...
0 ... 1
如何使用sql生成下表?
col_name min max count
col_1 1 2 2
col_2 -2 2 3
...
col_n 1 3 2
我基本上认为我需要转向某个地方,但我无法弄清楚如何
谢谢!
答案 0 :(得分:2)
使用unpivot
应该可以使用,但您必须提前指定所有列。如果这不实用,您可能需要研究动态SQL解决方案。
select
col as col_name,
min(val) as min,
max(val) as max,
count(val) as count
from (
select col, val
from t -- your table here
unpivot (
val for col in (col_1, col_2, col_n) -- your columns here
) u
) r
group by col;
示例SQL Fiddle(Oracle 11g R2)
答案 1 :(得分:1)
select colname, min(val), max(val), count(*)
from (
select 'col_1' as colname,
col_1 as val
from t
union
select 'col_2',
col_2
from t
-- and so on
) x
where val is not null
group by colname
这是另一种方法。感谢JPW的建议。