phpMyAdmin
 sql >> Datenbank >  >> Database Tools >> phpMyAdmin

SQL-Abfrage:Finden Sie maximal 2 von 3 Zahlen und speichern Sie sie in einer anderen Spalte

Betrachten Sie Folgendes

mysql> create table test (sub1 int, sub2 int , sub3 int);
Query OK, 0 rows affected (0.11 sec)

mysql> insert into test values (20,30,40),(10,40,50),(30,10,20);
Query OK, 3 rows affected (0.08 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> select * from test ;
+------+------+------+
| sub1 | sub2 | sub3 |
+------+------+------+
|   20 |   30 |   40 |
|   10 |   40 |   50 |
|   30 |   10 |   20 |
+------+------+------+

Also um den max1 zu bekommen und max2 aus den Spalten können Sie greatest verwenden Funktion.

select * ,
greatest(sub1,sub2,sub3) as max1 , 
greatest(
 case 
  when greatest(sub1,sub2,sub3) = sub1 then 0 else sub1 
 end,
 case 
  when greatest(sub1,sub2,sub3) = sub2 then  0 else sub2 
 end, 
 case 
  when greatest(sub1,sub2,sub3) = sub3 then 0 else sub3 
 end
) as max2 from test ;

Dadurch erhalten Sie etwas wie

+------+------+------+------+------+
| sub1 | sub2 | sub3 | max1 | max2 |
+------+------+------+------+------+
|   20 |   30 |   40 |   40 |   30 |
|   10 |   40 |   50 |   50 |   40 |
|   30 |   10 |   20 |   30 |   20 |
+------+------+------+------+------+

Sie können dies für den Update-Befehl verwenden als

update table_name
set 
max1 = greatest(sub1,sub2,sub3),
max2 = greatest(
 case 
  when greatest(sub1,sub2,sub3) = sub1 then 0 else sub1 
 end,
 case 
  when greatest(sub1,sub2,sub3) = sub2 then  0 else sub2 
 end, 
 case 
  when greatest(sub1,sub2,sub3) = sub3 then 0 else sub3 
 end
) 

Um den Durchschnitt von max1 und max2 zu erhalten und als

zu aktualisieren
update table_name
set 
`average`
= ( 
   greatest(sub1,sub2,sub3)+
   greatest(
    case 
      when greatest(sub1,sub2,sub3) = sub1 then 0 else sub1 
    end,
    case 
      when greatest(sub1,sub2,sub3) = sub2 then  0 else sub2 
    end, 
    case 
      when greatest(sub1,sub2,sub3) = sub3 then 0 else sub3 
    end
     )
)/2 ;