1.pgsql对数据进行日,周,月,年,时,分的统计
本文参考于:Postgresql数据数据库中按日、月、周、年、时、分,30分钟的统计解决方案 ,并在后面添加了自己开发项目中遇到的一些问题。
对要统计的时间字段进行字符转换处理,再按照其分组即可实现对数据进行日,周,月,年,时,分的统计。主要用到to_char()
函数。
-
按年统计:
'yyyy'
to_char( row_date,'yyyy' ) AS row_date2 from xxx GROUP BY to_char( row_date,'yyyy' )
-
按月统计:
'yyyy-MM'
to_char(row_date, 'yyyy-MM') AS row_date2 from xxx GROUP BY to_char(row_date, 'yyyy-MM')
-
按日统计:
'yyyy-MM-dd'
to_char(row_date, 'yyyy-MM-dd') AS row_date2 from xxx GROUP BY to_char(row_date, 'yyyy-MM-dd')
-
按小时统计:
'yyyy-MM-dd HH'
to_char(row_date, 'yyyy-MM-dd HH') AS row_date2 from xxx GROUP BY to_char(row_date, 'yyyy-MM-dd HH')
-
按分钟统计:
'yyyy-MM-dd HH:mm'
to_char(row_date, 'yyyy-MM-dd HH:mm' ) AS row_date2 from xxx GROUP BY to_char(row_date, 'yyyy-MM-dd HH:mm')
mybatis操作sql语句时,如果要动态决定按年或者月来统计的话,可以将to_char()
函数的第二个参数作为变量传递,【注意】这个变量要用${}
的方式获取,并且不要忘记加''
。
比如:
<select id="getYmStatis" parameterType="String" resultType="xxx.YearOrMonthVo">
select to_char(createtime, '${form}') as t, sum(price) as money, count(id) as num
from xxx
where result = 't'
group by to_char(createtime, '${form}')
</select>
2. mysql 对数据进行年月日的统计
1、每年
select year(ordertime) 年,
sum(Total) 销售合计
from 订单表
group by year(ordertime)
2、每月
select year(ordertime) 年,
month(ordertime) 月,
sum(Total) 销售合计
from 订单表
group by year(ordertime), month(ordertime)
3、每日
select year(ordertime) 年,
month(ordertime) 月,
day(ordertime) 日,
sum(Total) 销售合计
from 订单表
group by year(ordertime), month(ordertime), day(ordertime)