SQL行明智的总价值
我有一个表命名为calcu
SQL行明智的总价值
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
我需要row wise total value
。我的意思是在新列total
中,它将是(s1 + s2 + s3 + s4)即(7 + 4 + 8 + 9)= 28 where id=1
,(12 + 15 + 17 + 19)= 63 where id=2
,(28 + 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
它导致所有总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
;
如果你在SQL Fiddle中仔细检查你的答案,那么'min_value列已经被改变了',这是最低值的列,也就是在所有字段明智地合计之后,如s1 sum = 47,s2 sum = 32,s3 sum = 44,s4 sum = 38 –
所以你想要这样的东西:http://sqlfiddle.com/#!9/31579c/36 – Serge
select c.id,
c.date, c.name, c.s1, c.s2, c.s3, c.s4,
least(s1,s2,s3,s4) Minvalue,
(s1+s2+s3+s4) Total
from calcu c
我试图简化了查询。所以你正在寻找s1,s2,s3和s4中的最小值。你可以用最少的功能来实现。你需要所有四个'的专栏。只需添加他们
SELECT *,S1 + S2 + S3 + S4的共有来自calcu
只有代码的答案对社区没有用处。请看[如何回答](http://*.com/questions/how-to-answer) – abpatil
提示:'S1 + S2 + S3 + d4'。 –