2017-10-10 49 views
-1

我有一个名为calcu最小值列计算在SQL分组总

id date  name  s1  s2  s3  s4  min_value 
1 2/10/2017 dicky 7  4  8  9  [4] 
2 2/10/2017 acton 12  15  17  19  [15] 
3 2/10/2017 adney 28  13  19  10  [13] 

如果I总在单个日期的所有字段表,则结果将是

2/10/2017   47  32  44  38 

这里最小值是32。这意味着最小值栏是s2。这就是为什么我分别在表calcumin_value字段中输入s2 field value

我需要如何通过SQL查询来完成min_value字段?

我正在使用MYSQL数据库。

plz显示SQL查询和查询结果。

+2

请。标记您正在使用的DBMS(MySQL,MS SQL Server,Oracle等)。 –

+0

你可以看到这个......它对你有帮助。 https://stackoverflow.com/questions/10742616/get-column-name-which-has-the-max-value-in-a-row-sql –

+0

详细阐述你的问题。你的预期产出是多少? –

回答

0

您想先查找最小总和的列,然后在查询中使用该列。所以你需要一个子查询,你可以将每个数据与其他数据进行比较,并记住列名。然后在主查询中使用该列名称来检查显示哪个值。

select 
    c.id, c.date, c.name, c.s1, c.s2, c.s3, c.s4, 
    case 
    when col.colname = 's1' then c.s1 
    when col.colname = 's2' then c.s2 
    when col.colname = 's3' then c.s3 
    when col.colname = 's4' then c.s4 
    end as min_value 
from calcu c 
cross join 
(
    select 
    case 
     when sum(s1) <= sum(s2) and sum(s1) <= sum(s3) and sum(s1) <= sum(s4) then 's1' 
     when sum(s2) <= sum(s1) and sum(s2) <= sum(s3) and sum(s2) <= sum(s4) then 's2' 
     when sum(s3) <= sum(s1) and sum(s3) <= sum(s2) and sum(s3) <= sum(s4) then 's3' 
     else                  's4' 
    end as colname 
    from calcu 
) col; 

的改变SQL小提琴:http://sqlfiddle.com/#!9/31579c/3

+0

我的问题已解决。现在我可以获得明智的总价值吗?我的意思是在一个新的'total'列中,它将是(7 + 4 + 8 + 9)= 28其中id = 1,(12 + 15 + 17 + 19)= 63其中id = 2,(28 + 13 + 19 + 10)= 70,其中id = 3。 –

+0

检查我的问题在这里http://sqlfiddle.com/#!9/31579c/5 –

+0

为什么你把'sum(c.s1 + c.s2 + c.s3 + c.s4)'?它只是'c.s1 + c.s2 + c.s3 + c.s4'没有'sum',因为您只想在行本身中添加值,而不是在多行中汇总数据。 http://sqlfiddle.com/#!9/31579c/40 –