我有一个名为result的表,其中包含列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代码吗?
更新
我希望将最大数量和第二个最大数量除以2,而不是将最大数量存储到max1
,将第二个最大数量存储到max2
,而不是将其存储在average
列中将其存储在max1
和max2
中。
表示我不想要两个额外的列max1
和max2
来存储最大值和第二个最大值,然后添加它并将其除以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
答案 0 :(得分:1)
考虑以下
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 |
+------+------+------+
因此,要从列中获取max1
和max2
,您可以使用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 ;