[英]SQL column calculation mininimum value
I have a table named calcu
我有一张叫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. 由于最小列值是s2
[32],因此s2
值= min_value
列。
check sqlfiddle here 在这里检查sqlfiddle
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. 但是,当s1, s2, s3, s4
任何字段的值等于[ see below example
]与任何字段时,则min_value字段加倍,所有列加倍。 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
, 在这里,最小值列是s3
和s4
。
I require any column within s3 or s4
it means either s3
or s4
column will be filled in the min_value
column. 我需要s3 or s4
任何列,这意味着s3
或s4
列将填充在min_value
列中。
see the problem here with sqlfiddle 在这里看到问题与sqlfiddle
I am using MySQL. 我正在使用MySQL。
Based on your sqlfiddle, you need to add a GROUP BY outside of the nested queries in order to achieve what you want. 根据您的sqlfiddle,您需要在嵌套查询之外添加GROUP BY,以实现所需的功能。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.