rocky a
rocky a

Reputation: 144

SQL column calculation mininimum value

I have a table named 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

Here as minimum column value is s2[32], that's why s2 value = min_value column.

check sqlfiddle here

Now there is no problem. But when any of the fields within s1, s2, s3, s4 value equals [see below example] with any field then min_value field doubles and all column doubles. Example:

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

Here minimum value columns are s3 ans s4,

I require any column within s3 or s4 it means either s3 or s4 column will be filled in the min_value column.

see the problem here with sqlfiddle

I am using MySQL.

Upvotes: 1

Views: 68

Answers (1)

AlexCode
AlexCode

Reputation: 653

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

Upvotes: 2

Related Questions