我想获得每月的新用户数。应该以该月第一天的0:00h的UTC时间戳(以毫秒为单位,Long
表示一个月)。
这种方法可以解释我想做什么:
实体
class User {
@NotNull
private Long createdAt; // utc timestamp in ms
}
存储库
public interface UserRepository extends CrudRepository<User, Long> {
@Query("SELECT new UserRepository$NewUser(to_start_of_month_in_ms(user.createdAt), count(user.id)) "
+ "FROM User user "
+ "GROUP BY to_start_of_month_in_ms(user.createdAt) ")
List<NewUser> findNewUsersPerMonth();
@Getter
@AllArgsConstructor
public static class NewUser {
private Long startOfMonth; // utc timestamp in ms
private Integer count;
}
}
to_start_of_month_in_ms
有什么用,即如何从group by子句的createdAt
字段中得出月初。该怎么办
@Query
看起来像什么?
答案 0 :(得分:0)
我认为在JPQL中是不可能的,因为它不支持日期截断等。对于PSQL使用本机查询,我想到了这一点:
public interface CountPerMonth {
Integer getCount(); // count within the month
Long getStartOfMonth(); // timestamp in ms
}
@Query(nativeQuery = true, value = ""
+ "SELECT COUNT(u.id) AS count, "
+ " DATE_PART('EPOCH', DATE_TRUNC('MONTH',TO_TIMESTAMP(u.created_at/1000) AT TIME ZONE 'UTC'))*1000 AS startOfMonth "
+ "FROM user u "
+ "GROUP BY DATE_TRUNC('MONTH',TO_TIMESTAMP(u.created_at/1000) AT TIME ZONE 'UTC') "
+ "ORDER BY startOfMonth ")
List<CountPerMonth> findNewUsersPerMonth();