【问题标题】:Minimum Value column calculation by grouping total in sql通过在sql中对总计进行分组来计算最小值列
【发布时间】:2018-03-21 09:13:55
【问题描述】:

我有一个名为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]

如果我在一个日期汇总所有字段,那么结果将是

    2/10/2017           47      32      44      38

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

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

我正在使用 MYSQL 数据库。

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

【问题讨论】:

  • 请。标记您正在使用的 DBMS(MySQL、MS SQL Server、Oracle 等)。
  • 你可以看到这个......它可能对你有帮助。 stackoverflow.com/questions/10742616/…
  • 详细阐述您的问题。您的预期输出是什么。

标签: mysql sql group-by sum min


【解决方案1】:

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

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

【讨论】:

  • 我的问题已经解决了。现在我可以按行获得总值吗?我的意思是在一个新列total 中,它将是 (7+4+8+9) = 28 其中 id=1, (12+15+17+19)=63 其中 id=2, (28+13+ 19+10)=70,其中 id=3 分别。
  • 你为什么放sum(c.s1 + c.s2 + c.s3 + c.s4)?只是c.s1 + c.s2 + c.s3 + c.s4 没有sum,因为您只想在行本身中添加值,而不是在多行上聚合数据。 sqlfiddle.com/#!9/31579c/40
  • 我明白我的错误了。如果不介意,还有一个问题,是否可以设置一个名为 min_total 的列,其中值为 min_total*4 即 4*4 = 16,其中 id 为 1。
  • id = 1 的情况下,您需要 4 对 1 的因子。为此使用另一个 case 表达式并相乘:case when c.id = 1 then 4 else 1 end * case when col.colname ... end as min_value.
  • 其实我不明白如何为min_total 列创建多重大小写查​​询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多