美文网首页
211024:按周统计的sql-时间转为周几-stream().

211024:按周统计的sql-时间转为周几-stream().

作者: 弹钢琴的崽崽 | 来源:发表于2021-10-24 19:47 被阅读0次

    一. postgresql中实现按周统计详解

    1. 第一种SQL

    select 
    row_time::DATE-(extract(dow from row_time::TIMESTAMP)-1||'day')::interval monday,
    count(*) amount
    from acd_details 
    where 1=1 
    GROUP BY row_time::DATE-(extract(dow from row_time::TIMESTAMP)-1||'day')::interval
    

    显示的日期为每周周一的时间,总共六条数据,第一周(2018-12-31-2019-01-06) 3条

    第二周(2019-01-07-2019-01-13) 2条,第三周(2019-01-14-2019-01-20) 1条。,至此大功告成。

    这种方式评论有人说不准确,使用需要自己验证一下

    有问题 ,虽然日期显示的是每周周一,但是统计的数据还是周日到下周周六算一周,

    2. 第二种sql

    pg数据库按周,月统计数据

    SELECT date_trunc('WEEK', insert_time) as insertDate, SUM(data_increment) as dataTotal,SUM(human_increment) as humanTotal  from human_data_sum t where t.idtype=? GROUP BY insertDate ORDER BY insertDate DESC
    
    SELECT date_trunc('MONTH', insert_time) as insertDate, SUM(data_increment) as dataTotal,SUM(human_increment) as humanTotal  from human_data_sum t where t.idtype=? GROUP BY insertDate ORDER BY  insertDate DESC
    

    3. 第三种sql

    按照当前时间+7天算一周,不是按照传统的周一到周日统计数据,没有数据不会显示某一周的数据为0,直接不显示,如有需要则在代码里面补充0。

    原理:数据的创建时间-开始统计的时间(参数)获得天数差,再除7,得到第几周,按照这个值分组来统计数据。

    SELECT  
    sum(fum.distributor_number) distributor_number,
    case when 
    ceiling(CAST(date_part('day',cast(fum.create_date as TIMESTAMP)-cast(to_date('2021-09-28', 'YYYY-MM-DD') as TIMESTAMP))/7 AS DECIMAL ( 9, 1 ))) = 0 then 1 else 
    ceiling(CAST(date_part('day',cast(fum.create_date as TIMESTAMP)-cast(to_date('2021-09-28', 'YYYY-MM-DD') as TIMESTAMP))/7 AS DECIMAL ( 9, 1 ))) end week
    FROM
    follow_up_manage fum 
    WHERE
    fum.doctor_code IN ( '19' ) and 
     fum.follow_up_way = 3 
    and fum.create_date >= '2021-09-28' and fum.create_date <= to_date('2021-10-15 15:47:48', 'YYYY-MM-dd hh24:mi:ss')
    GROUP BY
    week
    ORDER BY
    week 
    

    二. 计算指定格式日期转为星期几

    /**
         * 根据当前时间计算周几 的方法
         * 抽成方法 可以复用
         * 传入 时间时间类型字符串就可
         * 返回 传入时间为周几
         * */
    public String dateToWeek(String datetime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; //可以其他的表现形式
        Calendar cal = Calendar.getInstance();// 获取指定时间
        Date date;
        try {
            date = sdf.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        return weekDays[w];
    }
    

    三. stream().filter()的用法

    stream.filter一般适用于list集合,主要作用就是模拟sql查询,从集合中查询想要的数据。filter里面的参数user是指集合里面的每一项

    public class StreamTest{
        public static void main(String[] args){
            List<User> list = new ArrayList<>();
            //定义三个用户对象
            User user1 = new User();
            user1.setUsername("huxiansen");
            user1.setPassword("123456");
            User user2 = new User();
            user2.setUsername("huxianseng");
            user2.setPassword("123456");
            User user3 = new User();
            user3.setUsername("huxiansen");
            user3.setPassword("12345");
            //添加用户到集合中
            list.add(user1);
            list.add(user2);
            list.add(user3);
            
                //在集合中查询用户名为huxiansen的集合
                List<User> userList = list.stream().filter(user -> "huxiansen".equals(user.getUsername())).collect(Collectors.toList());
            //在集合中查询出第一个用户密码为123456的用户
            Optional<User> user = list.stream().filter(userTemp -> "123456".equals(userTemp.getPassword())).findFirst();
            
                System.out.println(userList);
            System.out.println(user);
        }
    }
    

    四. mybatis if-else(写法)

    1. mybaits 中没有else要用chose when otherwise 代替

    2. 范例一

    <!--批量插入用户-->
    <insert id="insertBusinessUserList" parameterType="java.util.List">
        insert into `business_user` (`id` , `user_type` , `user_login` )
        values
        <foreach collection="list" index="index" item="item" separator=",">
            <trim prefix="(" suffix=")" suffixOverrides=",">
                <choose>
                    <when test="item.id != null and item.id !=''">
                        #{item.id,jdbcType=CHAR},
                    </when>
                    <otherwise>
                        '',
                    </otherwise>
                </choose>
                <choose>
                    <when test="item.userType != null and item.userType !=''">
                        #{item.userType,jdbcType=VARCHAR},
                    </when>
                    <otherwise>
                        '',
                    </otherwise>
                </choose>
            </trim>
        </foreach>
    </insert>
    

    其中choose为一个整体
    when是if
    otherwise是else

    <select id="selectSelective" resultMap="xxx" parameterType="xxx">
        select
        <include refid="Base_Column_List"/>
        from xxx
        where del_flag=0
        <choose>
            <when test="xxx !=null and xxx != ''">
                and xxx like concat(concat('%', #{xxx}), '%')
            </when>
            <otherwise>
                and xxx like '**%'
            </otherwise>
        </choose>
    </select>
    

    下面就是MyBatis中的if....else...表示方法

    <choose>
        <when test="">
            //...
        </when>
        <otherwise>
            //...
        </otherwise>
    </choose>
    

    五. 计算两个时间差有几周

    // 计算两个时间差 有几周
    public static int dateDiff(Date d1, Date d2) {
        long n1 = d1.getTime();
        long n2 = d2.getTime();
        long diff = Math.abs(n1 - n2);
        diff /= 3600 * 1000 * 24;
        if(diff % 7 != 0)
            return (int)(diff / 7 + 1);
        return (int)(diff / 7);
    }
    

    相关文章

      网友评论

          本文标题:211024:按周统计的sql-时间转为周几-stream().

          本文链接:https://www.haomeiwen.com/subject/ackdaltx.html