SQL列计算最小值

时间:2017-10-12 09:15:15

标签: mysql sql min calculation

我有一个名为calcu

的表格
id  date       name     s1       s2      s3     s4       min_value
1   10/10/2017  dicky    7        4       8      9       [4]
2   10/10/2017  acton    12      15       17     19      [15]
3   10/10/2017  adney    28      13       19     14      [13]
------------------------------------------------------------------
when total by date       47      32       44     42

此处最小列值为s2 [32],这就是s2值= min_value列的原因。

check sqlfiddle here

现在没有问题。但是当s1, s2, s3, s4值中的任何字段等于[see below example]且任何字段时,min_value字段将翻倍,所有列都会翻倍。 例如:

id  date       name     s1       s2      s3     s4       min_value
1   10/10/2017  dicky    7       24       8      11       [8]/[11]
2   10/10/2017  acton    12      15       17     19      [17]/[19]
3   10/10/2017  adney    28      13       19     14      [19]/[14]
------------------------------------------------------------------
when total by date       47      52       44     44

此处最小值列为s3 ans s4

我需要s3 or s4中的任何列,这意味着s3列中将填充s4min_value列。

see the problem here with sqlfiddle

我正在使用MySQL。

1 个答案:

答案 0 :(得分:2)

Based on your sqlfiddle, you need to add a GROUP BY outside of the nested queries in order to achieve what you want.

select c.id, c.date, c.name, c.s1, c.s2, c.s3, c.s4, 
    case v.s 
        when 1 then c.s1
        when 2 then c.s2
        when 3 then c.s3
        when 4 then c.s4
    end as min_value
from calcu c
join (
    select date, s, sum(val) val_sum
    from (                                   #unpivot your data
        select date, s1 as val, 1 as s
        from calcu
        union all
        select date, s2 as val, 2 as s
        from calcu
        union all
        select date, s3 as val, 3 as s
        from calcu
        union all
        select date, s4 as val, 4 as s
        from calcu
    ) x
    group by date, s
) v on c.date = v.date
where not exists (  #we are only interested in the minimum val_sum above
    select 1
    from (                                 #note this is the same derived table as above
        select date, s, sum(val) val_sum
        from (
            select date, s1 as val, 1 as s
            from calcu
            union all
            select date, s2 as val, 2 as s
            from calcu
            union all
            select date, s3 as val, 3 as s
            from calcu
            union all
            select date, s4 as val, 4 as s
            from calcu
        ) x
        group by date, s
    ) v2
    where v2.date = v.date
    and v2.val_sum < v.val_sum

) GROUP BY c.id # This is the addition you need

See a running solution here