mysql查询最近7天的数据,没有数据自动补0 ,用于echarts图展示

select DATE( createtime) date , createtime, count(1) as count   from  order表  where DATEDIFF( now(), createtime)<=7
 group by date ;

12 月九号没有; 

给他在关联一张日期的表; 

--生成从今天开始完整的7天日期

 

DECLARE @LastSevenDay table

(

day date

)

DECLARE @StartDay date = GETDATE();

DECLARE @InsertDay date = @StartDay;

WHILE DATEDIFF(DAY,@InsertDay,@StartDay) < 7

BEGIN

INSERT INTO @LastSevenDay

VALUES ( @InsertDay)

SET @InsertDay = DATEADD(day,-1,@InsertDay)

END

--生成最后结果

SELECT DATEPART(day,lsd.day) AS '日期' ,COUNT(orders.id) AS '订单量'

FROM @LastSevenDay AS lsd

LEFT JOIN orders

ON lsd.day = CONVERT(varchar(10),orders.ordertime,120)

GROUP BY lsd.day

 但是呢, 我们不想这么麻烦;  一个SQL 就可以;  

套一层 : 

select a.click_date,ifnull(b.count,0) as count
from (
    SELECT curdate() as click_date
    union all
    SELECT date_sub(curdate(), interval 1 day) as click_date
    union all
    SELECT date_sub(curdate(), interval 2 day) as click_date
    union all
    SELECT date_sub(curdate(), interval 3 day) as click_date
    union all
    SELECT date_sub(curdate(), interval 4 day) as click_date
    union all
    SELECT date_sub(curdate(), interval 5 day) as click_date
    union all
    SELECT date_sub(curdate(), interval 6 day) as click_date
) a left join (
  -- 原来的sql
select DATE( createtime) date , createtime, count(1) as count   from order表  where DATEDIFF( now(), createtime)<=7
 group by date ) b on a.click_date = b.date;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值