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

how to use 'select' in 'case when then' in mysql?

我的mysqltable是这样的:

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

有两个args:start和结尾, 我想要的是这样的:

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)