SQL 查询:查找 3 个数字中的最大 2 个并将其存储在另一列中

SQL Query : Find max 2 of 3 number and store it in another column

我有一个 table 的命名结果,其中包含列 name, rollno, sub1, sub2, sub3, max1, max2 等。 sub1, sub2, sub3 将存储获得的分数。我想找到 sub1, sub2, sub3 的最大值并将其存储在 max1 中并找到 sub1, sub2, sub3 的第二个最大值并将其存储在 max2.

示例

sub1  sub2  sub3      max1  max2
10     15    20        20    15
40     10    25        40    25
33     64    51        64    51

谁能告诉我 sql 代码?

更新

我不想将最大数存储到 max1 并将第二大数存储到 max2,而是想将最大数和第二大数除以 2 并将其存储在 average 中列而不将其存储在 max1max2 中。

表示我不想要两个额外的列 max1max2 来存储最大值和第二个最大值,然后将其相加并除以 2 然后将其存储在 average 中。我想做平均直接。

请更新代码。

例子

sub1  sub2  sub3   average

10     15    20     17.5   ( (Maximum + Second Maximum)/2 )
40     10    25     32.5   
33     64    51     57.5  

考虑以下

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 |
+------+------+------+

因此,要从列中获取 max1max2,您可以使用 greatest 函数。

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 ;

这会给你一些东西

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

您可以将其用于更新命令,如

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
) 

获取 max1 和 max2 的平均值并更新为

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 ;