Click here to Skip to main content
15,889,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
create table numb_tab(col_1 int, col_2 int,col_3 int)


insert into numb_tab values(12,45,23),(23,87,37),(2,34,13)

my question is how to return MIN and MAX (2 and 87) values from above table (numb_tab)
and how to write the query and how many methods are there ?

can you please give me answer................?
Posted

Solution 1 is very good. You can do it the same with CTE[^]:
SQL
;WITH MinMaxVal
AS
(
	SELECT col_1 As MyVal
	FROM @numb_tab
	UNION ALL
	SELECT col_2 As MyVal
	FROM @numb_tab
	UNION ALL
	SELECT col_3 As MyVal
	FROM @numb_tab
)
SELECT MIN(MyVal) AS MinVal, MAX(MyVal) AS MaxVal
FROM MinMaxVal
--uncomment below line if execution failed ;)
--OPTION (MAXRECURSION 0)
 
Share this answer
 
You can't specifically do that - you can't say MAX(List of columns), so it gets more complex. There are a couple of solutions here: http://stackoverflow.com/questions/71022/sql-max-of-multiple-columns[^] - they are date related, but its the same thing with integers.
Obviously you would need to duplicate it for max and min.
 
Share this answer
 
I don't know if there are best ways, but this works
SQL
SELECT MIN(col) AS Min, MAX(col) AS Max FROM (
    SELECT col_1 AS col FROM numb_tab 
    UNION SELECT col_2 FROM numb_tab
    UNION SELECT col_3 FROM numb_tab) t
 
Share this answer
 
Comments
Maciej Los 20-May-13 16:12pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900