简体   繁体   English

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

[英]Minimum Value column calculation by grouping total in sql

I have a table named calcu我有一个名为calcu的表

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]

If I total all fields in a single date then the result will be如果我在一个日期汇总所有字段,那么结果将是

    2/10/2017           47      32      44      38

Here minimum value is 32 .这里的最小值是32 It means minimum value column is s2 .这意味着最小值列是s2 That's why I input s2 field value in min_value field in table calcu respectively.这就是为什么我分别在表calcu min_value字段中输入s2 field value

I need how will I complete min_value field through SQL query?我需要如何通过 SQL 查询完成 min_value 字段?

I am using MYSQL database.我正在使用 MYSQL 数据库。

Plz show SQL query and query result.请显示 SQL 查询和查询结果。

You want to find the column with the minimum sum first and then use that column in your query.您想先找到总和最小的列,然后在查询中使用该列。 So you need a subquery where you compare each sum with the others and remember the column name.因此,您需要一个子查询,将每个总和与其他总和进行比较并记住列名。 Then in the main query use that column name to check which value to show.然后在主查询中使用该列名来检查要显示的值。

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;

The altered SQL fiddle: http://sqlfiddle.com/#!9/31579c/3更改后的 SQL 小提琴: http ://sqlfiddle.com/#!9/ 31579c/3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM