gpt4 book ai didi

mysql - 如何在mysql中使用 'select'中的 'case when then'?

转载 作者:行者123 更新时间:2023-11-29 12:02:35 26 4
gpt4 key购买 nike

我的mysql表是这样的:

id     value
1 10
2 20
3 30
4 40
5 50

有两个参数:start 和 end,我想要的是这样的:

when start=end, the result is 0
when start>end, the result is 'sum(value) where id<=start and id>end'
when start<end, the result is 'sum(value) where id>start and id<=end'

如何编写sql来获取结果?也许“case when then”是一个不错的选择,但我不知道如何写。

最佳答案

您可以将此逻辑放入 case 语句中,如下所示:

select (cast when @start = @end then 0
when @start > @end
then sum(case when id <= @start and id >= @end then value end)
when @start < @end
then sum(case when id > @start and id <= @end then value end)
end)
from table t;

您的逻辑非常接近这个更简单的版本:

select sum(case when id > least(@start, @end) and
id <= greatest(@start, @end)
then value else 0
end)

关于mysql - 如何在mysql中使用 'select'中的 'case when then'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32131135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com