In Oracle (instances that support univot)
SELECT MyID, MAX(GreatestVal) FROM figures UNPIVOT ( GreatestVal FOR MyID IN (col_1, col_2, col_3,...) );
The Oracle query is not verified because I do not have a convenient instance. More detailed information about univot is located here , and it does the same as without it.
MySQL I'm not sure how to do this in MySQL, but I can investigate, because I have the opportunity (if someone does not beat me to it. ;-))
The following are SQL Server answers:
Doing this in UDF is not very good, because all input parameters will be REQUIRED in each case. If you manage to implement it as a stored procedure, you can specify default values ββfor the input parameters and call them with a dynamic number of columns. In any case, you will have to choose the maximum number of input parameters. Here is an example in UDF on SQL Server:
SELECT dbo.GREATESTof3(col_1, col_2, col_3) FROM figures; CREATE FUNCTION GREATESTof3(@col_1 sql_variant = null, @col_2 sql_variant = null, @col_3 sql_variant = null) RETURNS sql_variant AS BEGIN DECLARE @GreatestVal sql_variant DECLARE @ColumnVals TABLE (Candidate sql_variant) INSERT INTO @ColumnVals SELECT @col_1 UNION ALL SELECT @col_2 UNION ALL SELECT @col_3 SELECT @GreatestVal = MAX(Candidate) FROM @ColumnVals RETURN @GreatestVal END
To do this, you will need a new UDF for each variant of the number of input parameters, or create one that can take a larger number, but then in the UDF call you need to either specify some value for each unused parameter (null) or specify a default value.
Alternatives:
This gives the maximum value of three columns from the entire table and it will be easier to have a dynamic number of columns:
SELECT MAX([Value]) AS Greatest FROM figures UNPIVOT ( [Value] FOR ColumnName IN ([Col_1], [Col_2], [Col_3]) ) AS unpvt
Assuming you have some kind of rowid or another column that you want in the output so that you can get the largest value from the specified columns for each row, you can do something like this:
SELECT RowID, MAX([Value]) AS Greatest FROM figures UNPIVOT ( [Value] FOR ColumnName IN ([Col_1], [Col_2], [Col_3]) ) AS unpvt GROUP BY RowID