通过在 sql 中对总计进行分组来计算最小值列

Minimum Value column calculation by grouping total in sql

我有一个名为 calcu

的 table
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]

如果我对一个日期的所有字段进行总计,那么结果将是

    2/10/2017           47      32      44      38

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

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

我正在使用 MYSQL 数据库。

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

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

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;

修改后的SQLfiddle:http://sqlfiddle.com/#!9/31579c/3