Mysql SQL行总值
我有一个名为Mysql SQL行总值,mysql,sql,row,Mysql,Sql,Row,我有一个名为calcu id date name s1 s2 s3 s4 min_value 1 02/10/2017 dicky 7 4 8 9 4 2 02/10/2017 acton 12 15 17 19 15 3 02/10/2017 adney 28 13 19
calcu
id date name s1 s2 s3 s4 min_value
1 02/10/2017 dicky 7 4 8 9 4
2 02/10/2017 acton 12 15 17 19 15
3 02/10/2017 adney 28 13 19 10 13
我需要行总值
。我的意思是在一个新的列中,它将是(s1+s2+s3+s4),即(7+4+8+9)=28,其中id=1
,(12+15+17+19)=63,其中id=2
,(28+13+19+10)=70,其中id=3
结果如下所示:
id date name s1 s2 s3 s4 min_value Total
1 02/10/2017 dicky 7 4 8 9 4 28
2 02/10/2017 acton 12 15 17 19 15 63
3 02/10/2017 adney 28 13 19 10 13 70
结果总共161行和3行变为1行
如何编写SQL查询?函数是一个聚合函数。与其他聚合一样,仅用于跨多行计算值
您希望在一行中添加值,因此只需使用+
运算符(括号是可选的)
对于查找行中的最小值,使用CASE WHEN
进行3次测试,比较S1、S2、S3和S4
这应该起作用:
select
c.id, c.date, c.name, c.s1, c.s2, c.s3, c.s4,
(c.s1 + c.s2 + c.s3 + c.s4) as total,
case
when c.s1 <= c.s2 and c.s1 <= c.s3 and c.s1 <= c.s4 then c.s1
when c.s2 <= c.s1 and c.s2 <= c.s3 and c.s2 <= c.s4 then c.s2
when c.s3 <= c.s2 and c.s3 <= c.s1 and c.s3 <= c.s4 then c.s3
when c.s4 <= c.s2 and c.s4 <= c.s3 and c.s4 <= c.s1 then c.s4
end as min_value
from calcu c
;
选择
c、 id、c.日期、c.名称、c.s1、c.s2、c.s3、c.s4、,
(c.s1+c.s2+c.s3+c.s4)总计,
案例
当c.s1
我试图简化查询。因此,您正在寻找s1、s2、s3和s4之间的最小值。你可以用最少的函数来实现。您总共需要四个“s”列。只需添加它们选择*,s1+s2+s3+s4作为计算中的合计值提示:s1+s2+s3+d4
。如果您仔细检查SQL FIDLE中的答案,最小值列已更改
这是最小值列,即在按列合计所有字段后,如s1 sum=47,s2 sum=32,s3 sum=44,s4 sum=38仅代码的答案对社区没有用处。请看
id date name s1 s2 s3 s4 min_value
1 02/10/2017 dicky 7 4 8 9 4
2 02/10/2017 acton 12 15 17 19 15
3 02/10/2017 adney 28 13 19 10 13