sql - Select MAX and MIN from multiple columns -
i can max()
, min()
multiple columns in same table this:
select max(maximo) maximo, min(minimo) minimo from( select max(column1) maximo, min(column2) minimo table1 cond1= 'a' , cond2= 'x' union select max(column3) maximo, min(column4) minimo table1 cond1= 'a' , cond2= 'x' union select max(column5) maximo, min(column6) minimo table1 cond1= 'a' , cond2= 'x' union select max(column7) maximo, min(column8) minimo table1 cond1= 'a' , cond2= 'x' ) x
but looks ugly. trying use unpivot
:
select min (v) minvalue, max (v) maxvalue table1 unpivot ( v nvalue in ( column1, column2, column3, column4, column5, column6, column7, column8 ) ) u
and receiving following error:
[err] 42000 - [sql server]incorrect syntax near keyword 'for'.
what should be? thanks.
seems can write using cross apply
values
final result:
select maximo = max(maxval), minimo = min(minval) table1 t cross apply ( values (column1, column2), (column3, column4), (column5, column6), (column7, column8) ) c (maxval, minval) t.cond1= 'a' , t.cond2= 'x';
see sql fiddle demo. unpivots pairs of columns , can grab max
/min
of each column.
Comments
Post a Comment