1

I have a table: enter image description here

I need to get below result: enter image description here

The Code should select row where "Number" value is MIN. If there is "Unique_1" where "Unique_2" != MIN, then take columns where "Number" value is MAX.

Current code:

select  T1.Unique_1, 
    T1.Unique_2,
    Case WHEN  T2.MIN_Number is not NULL then  T2.MIN_Number ELSE T3.MAX_Number end as Number from Table_1 as T1 LEFT JOIN ( 
SELECT  Unique_1,
        MIN(Number) as MIN_Number
From Table_1 WHERE Unique_2 = 'MIN' 
GROUP BY Unique_1) AS T2 ON  T1.Unique_1 = T2.Unique_1 LEFT JOIN( 
SELECT  Unique_1, 
        MAX(Number) as MAX_Number 
From Table_1 WHERE Unique_2 = 'MAX' 
GROUP BY Unique_1) AS T3 ON  T1.Unique_1 = T3.Unique_1 

Hope I have clearly described the issue.

P.S. Thank you for your help and ideas.

Petras
  • 581
  • 2
  • 7
  • 17
  • DO NOT SHARE IMAGE OF DATA OR ERRORS https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors – TimLer May 19 '23 at 08:44

2 Answers2

3

You can do it using the conditional aggregation :

SELECT unique_1, CASE WHEN minVal IS NOT NULL THEN 'MIN' ELSE 'MAX' END AS 'unique_2',
       COALESCE(minVal, maxVal) as number
FROM (
  SELECT unique_1, MIN(CASE WHEN unique_2 = 'MIN' THEN Number END) AS minVal,
                   MAX(CASE WHEN unique_2 = 'MAX' THEN Number END) AS maxVal
  FROM mytable
  group by unique_1
) AS s

Result :

unique_1    unique_2    number
222         MIN         1
333         MIN         1
444         MAX         3

Demo tested on mysql here

SelVazi
  • 10,028
  • 2
  • 13
  • 29
2

Here is the solution (Here is a demo on mariadb 10.9):

select unique_1, unique_2, min(number) as number
from table_1
where unique_2 = 'MIN'
group by unique_1, unique_2
union all
select unique_1, unique_2, max(number) as number
from table_1 ta
where unique_2 = 'MAX'
and not exists (select null
                  from table_1 tb
                  where tb.unique_1 = ta.unique_1
                  and tb.unique_2 = 'MIN')
group by unique_1, unique_2;

 unique_1 | unique_2 | number 
----------+----------+--------
      222 | MIN      |      1 
      333 | MIN      |      1 
      444 | MAX      |      3 
Jérôme Radix
  • 10,285
  • 4
  • 34
  • 40