查找最小值列和最小值列名称

时间:2017-10-28 10:01:42

标签: mysql sql

我有一个名为formal的表:

id date         name     d1    d2     d3     d4
1  20/10/2017   bimal    6     7      8      9
2  20/10/2017   kumar    13    10     11     12
3  20/10/2017   aman     16    17     14     15
4  20/10/2017   halim    25    21     23     16

我需要明智的列。值。即d1 = 6 + 13 + 16 + 25 = 60,d2 = 7 + 10 + 17 + 21 = 55,d3 = 8 + 11 + 14 + 23 = 56,d4 = 9 + 12 + 15 + 19 = 52

此处下栏为d4。所以我的min _value col将是9,12,15,19。

我的下一栏是min_value_col。它将简单地为d4,d4,d4,d4。

现在我的输出表格如下:

id date         name     d1    d2     d3     d4   min_value    min_value_col
1  20/10/2017   bimal    6     7      8      9    9              d4
2  20/10/2017   kumar    13    10     11     12   12             d4
3  20/10/2017   aman     16    17     14     15   15             d4
4  20/10/2017   halim    25    21     23     16   16             d4

我需要分别通过mysql查询填充min_valuemin_value_col字段。

2 个答案:

答案 0 :(得分:0)

以下查询将同时提供min_valuemin_value_col

select id,fr_date,name,d1,d2,d3,d4,
    @min_value_col:=case when least_sum= sum_d1 then 'd1' when
    least_sum= sum_d2 then 'd2' when least_sum= sum_d3 then 'd3' 
    when least_sum= sum_d4 then 'd4' end min_value_col,

    case @min_value_col when 'd1' then d1 when 'd2' then d2
    when 'd3' then d3 when 'd4' then d4 end min_value
from formal, 
    (select sum(d1) sum_d1,sum(d2) sum_d2,sum(d3) sum_d3, sum(d4) sum_d4, 
     least(sum(d1),sum(d2),sum(d3),sum(d4)) least_sum 
            from formal) TEMP

答案 1 :(得分:0)

你似乎想要:

select f.*,
       (case ff.least_col
             when 'd1' then d1
             when 'd2' then d2
             when 'd3' then d3
             when 'd4' then d4
        end) as least_val,
       ff.least_col
from formal f cross join
     (select least(sum(d1), sum(d2), sum(d3), sum(d4)) as least_val,
             (case least(sum(d1), sum(d2), sum(d3), sum(d4))
                   when sum(d1) then 'd1'
                   when sum(d2) then 'd2'
                   when sum(d3) then 'd3'
                   when sum(d4) then 'd4'
              end) as least_col
      from formal
     ) ff;