最近在写报表统计,用的是postgresql,联合之前写的票据报表统计,写一下罕用的语句。

  1. 存在可重复使用的查问后果,不蕴含参数的,能够创立长期表。
  2. 数据表如果须要存大量数据,为了进步查问速度能够创立索引。索引的设置可依据理论查问表的条件。
    create index index_name on tb_example
  3. 将一列字符串数据拆分为多列数据,例如"合肥市-庐阳区-杏花街道"转为"合肥市","庐阳区","杏花街道"。应用split(字段名,分隔符,index)办法,截取字符串总substr(字符串,长度)

    select tb_no, split(area_name,'-',1) as city,split(area_name,'-',2) as country,split(area_name,'-',3) as town from tb_example
  4. 多条件查问的状况下正当使用case when。比方想要统计一张表中status在不同状态下的数量。然而须要联表查问的时候须要留神将须要依据条件统计的独自拎进去。(A表查问tb_example1中不同状态的统计量,表B统计tb_example2中index大于0的no个数<去重>)

    select A.*, B.uniqueNum from (select no,sum(case status when '01' then 1 else 0 end) as num1,sum(case status when '02' then 1 else 0 end) as num2from tb_example1 group by no) A,(select no, case when index > 0 then count(distinct(no)) else 0 end as uniqueNum  from tb_example2) Bwhere A.no = B.no
  5. 判断字符串是否蕴含采纳position(字符串1,字符串2)>0判断
  6. 获取某日期的周月年起止日期
weekStart timestamp := DATE_TRUNC('week', t_date) 所在周周一monthStart timestamp := DATE_TRUNC('month', t_date) 所在月初yearStart timestamp := DATE_TRUNC('year', t_date) 所在年初firstRace timestamp := DATE_TRUNC('quarter', t_date) - interval '1h' 所在季度初