mysql时间截取函数和实现数据累加
一、mysql之时间截取函数DATE_FORMAT
我有个datatime类型的数据,格式为yyyy-mm-dd hh-mm-ss ,现在我需要把这个数据分成两部分,分别为yyyy-mm-dd和hh-mm-ss,那么我就需要借助函数date_format()来实现。
例如我要把数据 '2019-06-13 07:07:46' 拆分为'2019-06-13' 和 '07:07:46',则我可以写成如下sql:
-- 格式也可以随时调整,可以去掉横杠- 和冒号:
select DATE_FORMAT(data_time,'%Y-%m-%d') as Date,
DATE_FORMAT(data_time,'%H:%i:%s') as date_time from ops_coupon;
二、mysql中实现数据累加
有三种方式,这里使用定义变量的方式实现数据累加,其他两种方式,参见参考原文。
通过定义变量实现数据累加,如下sql所示:
select date,sales,@cum_sales:=@cum_sales+sales as cum_sales
from sales,(select @cum_sales:=0)c
order by date asc;
-- 实际业务sql
set @beginTime = null ; -- 定义一个变量,设置值为空;
set @endTime = null ;
set @couponName=null;
set @rateAmount=null;
set @beginTime = '2020-01-20 00:00:00' ; -- 定义一个变量,并且设置值
set @endTime = '2021-03-23 00:00:00' ;
set @couponName='减息券';
set @rateAmount=0.3;
select createTime, @hisExchangeNum_sum:=@hisExchangeNum_sum+hisExchangeNum as hisExchangeNum_sum,-- 使用变量,并进行累加赋值
@hisUseNum_sum:=@hisUseNum_sum+hisUseNum as hisUseNum_sum,todayExchangeNum,todayUseNum
from (
select
createTime,
hisExchangeNum,hisUseNum,
todayExchangeNum,todayUseNum
from (SELECT
bb.*,cc.todayExchangeNum,cc.todayUseNum
FROM
(
SELECT DATE_FORMAT(b.create_time,'%Y%m%d') as createTime,
(COUNT(( CASE b.coupon_status WHEN '1' THEN '已使用' WHEN '2' THEN '未使用' WHEN '3' THEN '已失效' END ))) AS hisExchangeNum,
(COUNT(( CASE b.coupon_status WHEN '1' THEN '已使用' END ))) AS hisUseNum
FROM
ops_coupon a,
ops_coupon_relation_customer b
WHERE
a.enabled = '1'
AND b.enabled = '1'
AND a.id = b.coupon_id
AND a.coupon_cn_name = @couponName -- 直接使用变量,这里的值引用的是变量的值,因此修改条件可以直接修改变量值即可
AND a.coupon_rate_amount = @rateAmount
AND b.create_time >= @beginTime
AND b.create_time <= @endTime
GROUP BY createTime
) bb
LEFT JOIN
(
SELECT DATE_FORMAT(b.create_time,'%Y%m%d') as createTime,
(COUNT( ( CASE b.coupon_status WHEN '1' THEN '已使用' WHEN '2' THEN '未使用' WHEN '3' THEN '已失效' END ) )) AS todayExchangeNum,
(COUNT( ( CASE b.coupon_status WHEN '1' THEN '已使用' END ) )) AS todayUseNum
FROM
ops_coupon a,
ops_coupon_relation_customer b
WHERE
a.enabled = '1'
AND b.enabled = '1'
AND a.id = b.coupon_id
AND a.coupon_cn_name = @couponName
AND a.coupon_rate_amount = @rateAmount
AND b.create_time >= @beginTime
AND b.create_time <= @endTime
GROUP BY createTime
) cc
on 1=1
ORDER BY createTime asc ) dd
GROUP BY dd.createTime
) a,(select @hisExchangeNum_sum:=0,@hisUseNum_sum:=0) c;
ORDER BY createTime asc ;
参考博文:
(1) https://blog.csdn.net/qq_31476455/article/details/94718790 (时间截取函数)
(2)https://baijiahao.baidu.com/s?id=1665281520464858743&wfr=spider&for=pc (三种方式实现数据累加)
(3) https://blog.csdn.net/qq_33157666/article/details/87877246 (存储过程基础用法)