Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT min max and max min value from a part of a table in MySQL

Tags:

mysql

max

minmax

I want to select min max and max min values for each value in table1 from another table2. sample input

table2
name, value,y
f1, .01,.04
f1,.02,.05
f1,.05,.06
f1,.45,.07
f2,.03,.09
f2,.05,.02

table1
name, value
f1, .04
f2,.04

expected output
table3
name, value,min_max-value,max_min-value,y(min_max-value),y(max_min-value)
f1, .04,.02,.05,.05,.06
f2,.04,.03,.05,.09,.02
like image 552
Karunakar Avatar asked Sep 21 '13 08:09

Karunakar


People also ask

How do I get the maximum and minimum values from a table in SQL?

The SQL MIN() and MAX() FunctionsThe MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.

Can we use Max in WHERE clause in MySQL?

The MAX() function is used with the WHERE clause to gain further insights from our data. In SQL, the MAX() function computes the highest or maximum value of numeric values in a column.

Can we use min in WHERE clause?

You can get the lowest or minimum value using this function from any column, even you can filter the lowest or minimum value between specified expressions using the WHERE clause.

Can we use Min and Max together in SQL?

Using MIN() and MAX() in the Same QueryYou can use both the MIN and MAX functions in one SELECT . If you use only these functions without any columns, you don't need a GROUP BY clause.


1 Answers

You can get MAX and MIN values from t2 with the following query:

SELECT
    t1.name,
    t1.value,
    (SELECT min(value) FROM table2 t2 WHERE t2.name = t1.name),
    (SELECT MAX(value) FROM table2 t2 WHERE t2.name = t1.name)
FROM table1 t1

EDIT: To get the values closer to the t1.value and corresponding y value you could do:

SELECT 
    t1.NAME, 
    t1.value, 
    (SELECT MAX(t2.value)
      FROM table2 t2
      WHERE t2.NAME = t1.NAME AND t2.value < t1.value) AS maxmin, 
    (SELECT MIN(t2.value)
      FROM table2 t2
      WHERE t2.NAME = t1.NAME AND t2.value > t1.value) AS minmax, 
    (SELECT t2.y
      FROM table2 t2
      WHERE t2.NAME = t1.NAME AND t2.value = (
            SELECT MAX(t3.value)
            FROM table2 t3
            WHERE t3.NAME = t1.NAME AND t3.value < t1.value
            )) AS ymaxmin, 
    (SELECT t2.y
      FROM table2 t2
      WHERE t2.NAME = t1.NAME AND t2.value = (
            SELECT MIN(t3.value)
            FROM table2 t3
            WHERE t3.NAME = t1.NAME AND t3.value > t1.value
            )) AS yminmax
FROM table1 t1

see it in this fiddle

like image 132
Filipe Silva Avatar answered Sep 18 '22 00:09

Filipe Silva