MySQL : using sum in( case when ) statement shows 0 as result

标签 mysql

MySQL 的新手..所以请帮我解决这个基本代码.. 我有一个类似这样的查询...

select weekofyear(id_time),
(id),

@Tat1:=exp1,
@Tat2:=exp2,
@check1:=exp3,
@check2:=exp4, 
(case when @check2=0 then 
        (case when  (@Tat1>(@Tat2+30) or  (@check1=1 and (@Tat1>@Tat2+10)))  then 1  else 0 end)  
        else 
        (case when (@Tat1>(@Tat2+30) or  (@check1=1 and (@Tat1>@Tat2+20))) then 1 else 0 end) 
    end) as BO

from datb
where cid=18
and id_time between '2019-11-01 06:00:00' and '2019-11-25 06:00:00'

它给出了正确的结果-- here

但是我想在 case when 语句之后使用 sum 以便我可以获得总值,其中 BO=1 并按一年中的一周分组,所以我进行了以下更改-

select weekofyear(id_time),
count(id),

@Tat1:=exp1,
@Tat2:=exp2,
@check1:=exp3,
@check2:=exp4, 
sum(case when @check2=0 then 
        (case when  (@Tat1>(@Tat2+30) or  (@check1=1 and (@Tat1>@Tat2+10)))  then 1  else 0 end)  
        else 
        (case when (@Tat1>(@Tat2+30) or  (@check1=1 and (@Tat1>@Tat2+20))) then 1 else 0 end) 
    end) as BO

from datb
where cid=18
and id_time between '2019-11-01 06:00:00' and '2019-11-25 06:00:00'
group by weekofyear(id_time)

但它始终返回 0 作为输出。 输出——此处2

请帮忙,我不知道我在做什么错。

谢谢!

最佳答案

正如其他人已经说过的, session 变量可能是不可预测的(尤其是当聚合混入时)。也就是说,看起来您并没有使用 session 变量将值从一行传递到下一行(通常这样做),而只是为您不想重复的计算创建各种别名。

更好的处理方法是通过子查询。

SELECT woy, id, Tat1, Tat2, check1, check2
    , CASE 
        WHEN check2=0 THEN (
            CASE 
            WHEN (Tat1>(Tat2+30) OR (check1=1 AND (Tat1>Tat2+10))) THEN 1 
            ELSE 0 
            END
        )
        ELSE (
            CASE WHEN (Tat1>(Tat2+30) OR (check1=1 AND (Tat1>Tat2+20))) THEN 1 
            ELSE 0 
            END
        ) 
    END AS BO
FROM (
    SELECT WEEKOFYEAR(id_time) AS woy
        , id
        , exp1 AS Tat1
        , exp2 AS Tat2
        , exp3 AS check1
        , exp4 AS check2
    FROM datb
    WHERE cid=18
        AND id_time BETWEEN '2019-11-01 06:00:00' AND '2019-11-25 06:00:00'
) AS subQ
;

然后您可以调整上述聚合查询,或将其用作聚合外部查询的子查询。

关于MySQL : using sum in( case when ) statement shows 0 as result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59039684/

相关文章:

PHP、MySQL基于外部排序派优化排序

php - 使用 AJAX 从 SQL 获取信息并放入表中

php - Mysql查询比较字符串(varchar)作为整数

mysql - Ruby on Rails 安装问题 (Windows)

mysql 仅用一张表进行复杂选择

mysql - 将查询转换为嵌套查询

mysql - 将日期时间插入 MySQL 表超过 24 小时标记

php - 如何从 session ID 获取值

php - 哪个更快 : in_array or database queries?

php - Mysql搜索字段不同的顺序