使用SQL查询计算每一天

时间:2017-11-09 02:47:53

标签: mysql sql

我想显示一个带有SQL查询的表,如下所示:

react-php-v8js

我已经运行了我的查询:

select 
    tb_r_orderdata.finishtime as date ,
    count(*)sum all,
    sum(when status = 'SUCCESS' and issync = '1' then 1 else 0 end) sumpaid,
    sum(when status = 'SUCCESS' and issync in ('3', '4') then 1 else 0 end) sumfail,
    sum(when status = 'CLOSED' then 1 else 0 end) sumclose,
    sum(when status = 'Null' then 1 else 0 end) sumunflag
from 
    tb_r_orderdata;

但是当我执行它时,结果与我的预期不同。结果是这样的:

enter image description here

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您错过了GROUP BYCASE

select tb_r_orderdata.finishtime as date ,
       COUNT(*) as sumall,
       SUM(CASE WHEN status='SUCCESS' AND issync='1' then 1 ELSE 0 END) as sumpaid,
       SUM(CASE WHEN status='SUCCESS' AND issync in ('3','4') then 1 ELSE 0 END) as sumfail,
       SUM(CASE WHEN status='CLOSED' then 1 ELSE 0 END) as sumclose,
       SUM(CASE WHEN status is null then 1 ELSE 0 END) as sumunflag
from tb_r_orderdata
group by tb_r_orderdata.finishtime  ;

MySQL将布尔值视为数字上下文中的整数,使用" 1"为真和" 0"为假。您可以将查询简化为:

select o.finishtime as date ,
       COUNT(*) as sumall,
       SUM(status = 'SUCCESS' AND issync = '1') as sumpaid,
       SUM(status = 'SUCCESS' AND issync in ('3', '4')) as sumfail,
       SUM(status = 'CLOSED') as sumclose,
       SUM(status is null) as sumunflag
from tb_r_orderdata o
where tb_r_orderdata.finishtime is not NULL
group by o.finishtime  ;

这也会删除NULL完成时间。

答案 1 :(得分:0)

Explanation in comment for Gordon Linoff

对Gordon Linoff的评论中的解释

我已经尝试了你的答案,但是在表格顶部有记录NULL,我不知道为什么,你能解释一下吗

戈登·林诺夫的答案稍有改变

select tb_r_orderdata.finishtime as date ,
       SUM(CASE WHEN status='SUCCESS' AND issync='1' then 1 ELSE 0 END) as sumpaid,
       SUM(CASE WHEN status='SUCCESS' AND issync in ('3','4') then 1 ELSE 0 END) as sumfail,
       SUM(CASE WHEN status='CLOSED' then 1 ELSE 0 END) as sumclose,
       SUM(CASE WHEN status='NULL' then 1 ELSE 0 END) as sumunflag
from tb_r_orderdata
group by tb_r_orderdata.finishtime