最近做了一个日统计报表,一个非常简单的小查询,却引出了一些小问题,在这里记录一下:
1.首先是根据日期对每天进行数据统计
2.条件筛选时存在时间边界的问题
第一个问题
如何根据时间对数据进行每日的统计。首先,数据库有一张类似于下面的表–只关于时间 这样你就可以关联你所要统计的表的来进行按日统计。 这里我用到了几个点,可以注意一下:
1.对于当日数据为空的进行默认置零
2.关联时间表进行按日查询
3.对时间筛选条件进行边界处理
SELECT
date_format(date
,'%Y-%m-%d') as worktime
,
ifnull(pushmes
.waitPush
,0) as waitPush
,
ifnull(pushmes
.pushFail
,0) as pushFail
,
ifnull(pushmes
.pushPlatform
,'') as pushPlatform
,
ifnull(pushmes
.pushSuccess
,0) as pushSuccess
from work_date
LEFT JOIN
(SELECT
date_format(push_time
,'%Y-%m-%d') as pushdates
,
push_platform as pushPlatform
,
sum(case push_result when
-1 then
1 else 0 end
) waitPush
,
sum(case push_result when
1 then
1 else 0 end
) pushSuccess
,
sum(case push_result when
0 then
1 else 0 end
) pushFail
FROM
loan_app_push
<where>
<if test
="pushPlatform != null and pushPlatform != ''">
push_platform
= #
{pushPlatform
}
</if>
<if test
="startTime !=null and startTime!=''">
and push_time
>
;= DATE_FORMAT(#
{startTime
}, '%Y-%m-%d')
</if>
<if test
="endTime !=null and endTime!=''">
and push_time
<
;= DATE_FORMAT(#
{endTime
}, '%Y-%m-%d 23:59:59')
</if>
</where
>
group by pushdates
) as pushmes on pushdate
.pushdates
= work_date
.date
<where>
<if test
="pushPlatform != null and pushPlatform != ''">
pushmes
.pushPlatform
= #
{pushPlatform
}
</if>
<if test
="startTime !=null and startTime!=''">
and work_date
.date
>
;= DATE_FORMAT(#
{startTime
}, '%Y-%m-%d')
</if>
<if test
="endTime !=null and endTime!=''">
and work_date
.date
<
;= DATE_FORMAT(#
{endTime
}, '%Y-%m-%d')
</if>
</where
>
order by work_date
.date desc
</select
>
1.使用ifnull(pushmes.waitPush,0) as waitPush 对空字段进行置零操作,注意后面需要 重新as 一个新的字段名;
2.使用left join 对时间表及数据表进行关联,关联点为时间。这里讲数据表进行筛选过后生成一张临时数据表与时间表进行关联。
3.时间边界问题:这里用到了gt= 与lt= 大于小于等于,后面对时间进行格式化处理,但注意’%Y-%m-%d’格式化后默认的时间是当日时间的00:00:00,所以在endTime时,我们就要对其进行处理,手动更新时间为23:59:59,这样就可以查到结束日期那天的数据了。
4.另外补充一点,如果想要查询出每天的数据,没有数据的那天也要展示,那么最外面的筛选条件(时间表进行筛选)就起到了作用。
好了,暂时就这么多内容。
总结一下,要点:left join 、临时表、ifnull判断、date_format时间边界。
日拱一卒,得寸进尺。