pgsql统计时遇到的难题以及一些总结

1.pgsql对数据进行日,周,月,年,时,分的统计

本文参考于:Postgresql数据数据库中按日、月、周、年、时、分,30分钟的统计解决方案 ,并在后面添加了自己开发项目中遇到的一些问题。


对要统计的时间字段进行字符转换处理,再按照其分组即可实现对数据进行日,周,月,年,时,分的统计。主要用到to_char()函数。

  1. 按年统计:'yyyy'

    to_char( row_date,'yyyy' ) AS row_date2
    from xxx
    GROUP BY to_char( row_date,'yyyy' )
    
  2. 按月统计:'yyyy-MM'

    to_char(row_date, 'yyyy-MM') AS row_date2
    from xxx
    GROUP BY to_char(row_date, 'yyyy-MM')
    
  3. 按日统计:'yyyy-MM-dd'

    to_char(row_date, 'yyyy-MM-dd') AS row_date2
    from xxx
    GROUP BY to_char(row_date, 'yyyy-MM-dd')
    
  4. 按小时统计:'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')
    
  5. 按分钟统计: '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)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值