mysql - SQL行明智的总值(value)

标签 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    10      13        

This is my table in SQL Fiddle

我需要按行计算总值。我的意思是在新列 total 中,它将是 (s1 + s2 + s3 + s4) 即 (7+4+8+9) = 28 where id=1 , (12+15+17+19)=63 where id=2, (28+13+19+10)=70 where 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

see my problem here

结果全部161,3行变成1行。

如何编写SQL查询?

最佳答案

SUM() 函数是一个聚合函数。与其他聚合一样,它仅用于跨多行计算值。

你想在一行中添加值,所以只需使用 + 运算符(括号是可选的)。

至于找到行中的最小值,使用 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
;

参见 SQLFiddle

关于mysql - SQL行明智的总值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46740588/

相关文章:

mysql - 如何计算 MySQL 结果中的 has-many-through 关系

MySQL奇怪的FK错误

javascript - 在页面导航时更改 SQL 语句

mysql - 这个sql中的where子句会放在哪里?

sql - 将 Visual Foxpro 数据库导入到 SQL Server

javascript - 如何获取用 JQuery 单击的行的表格单元格

php - 无法将数据保存到具有复合主键的新表中

html - 导航栏没有获取页面的所有宽度

postgresql - Postgres 中的元组和行有什么区别?

php - 树节点 MySQL 到 PDO 语句