2017-10-14 59 views
1

我有一個表命名爲calcuSQL行明智的總價值

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 

see my problem here

它導致所有總161個3行成爲1行。

如何編寫SQL查詢?

+0

提示:'S1 + S2 + S3 + d4'。 –

回答

1

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

+0

如果你在SQL Fiddle中仔細檢查你的答案,那麼'min_value列已經被改變了',這是最低值的列,也就是在所有字段明智地合計之後,如s1 sum = 47,s2 sum = 32,s3 sum = 44,s4 sum = 38 –

+0

所以你想要這樣的東西:http://sqlfiddle.com/#!9/31579c/36 – Serge

0
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中的最小值。你可以用最少的功能來實現。你需要所有四個'的專欄。只需添加他們

0

SELECT *,S1 + S2 + S3 + S4的共有來自calcu

+0

只有代碼的答案對社區沒有用處。請看[如何回答](http://stackoverflow.com/questions/how-to-answer) – abpatil