使用 JOOQ 的日期时间字段按日期分组
Group by date using a datetime field with JOOQ
我有一个名为 delivery
的 table 和日期时间字段 delivery_time
。
+--------------------+------------------------------------------+------+-----+-------------------+
| Field | Type | Null | Key | Default |
+--------------------+------------------------------------------+------+-----+-------------------+
| delivery_time | datetime | YES | | NULL |
我想统计每个日期的送货情况。使用普通 sql 我可以做到这一点
select CAST(delivery_time as DATE) as date, count(*) as count from delivery group by CAST(delivery_time as DATE);
+------------+-------+
| date | count |
+------------+-------+
| 2021-04-21 | 1 |
| 2021-03-22 | 11 |
| NULL | 3 |
| 2021-03-21 | 1 |
| 2021-04-22 | 2 |
| 2021-04-30 | 1 |
+------------+-------+
但是当我尝试使用 JOOQ 执行此操作时,它无法正常工作(仅返回空行)
jooq.dsl()
.select(
date(Tables.DELIVERY.DELIVERY_TIME.toString()),
count()
)
.from(Tables.DELIVERY)
.groupBy(date(Tables.DELIVERY.DELIVERY_TIME.toString()))
.fetch()
谁能帮我用 jooq 写这个查询
您正在使用 Object.toString()
method, which is available on all Java objects for debugging purposes. In jOOQ, you're going to get a string representation of your column expression. There's no point in doing that in your case. Just use the DSL.cast()
方法,就像您使用 SQL 一样。
假设通常的静态导入:
import static org.jooq.impl.DSL.*;
import static org.jooq.impl.SQLDataType.*;
import static com.example.Tables.*;
写
jooq.dsl()
.select(cast(DELIVERY.DELIVERY_TIME, DATE), count())
.from(DELIVERY)
.groupBy(cast(DELIVERY.DELIVERY_TIME, DATE))
.fetch();
我有一个名为 delivery
的 table 和日期时间字段 delivery_time
。
+--------------------+------------------------------------------+------+-----+-------------------+
| Field | Type | Null | Key | Default |
+--------------------+------------------------------------------+------+-----+-------------------+
| delivery_time | datetime | YES | | NULL |
我想统计每个日期的送货情况。使用普通 sql 我可以做到这一点
select CAST(delivery_time as DATE) as date, count(*) as count from delivery group by CAST(delivery_time as DATE);
+------------+-------+
| date | count |
+------------+-------+
| 2021-04-21 | 1 |
| 2021-03-22 | 11 |
| NULL | 3 |
| 2021-03-21 | 1 |
| 2021-04-22 | 2 |
| 2021-04-30 | 1 |
+------------+-------+
但是当我尝试使用 JOOQ 执行此操作时,它无法正常工作(仅返回空行)
jooq.dsl()
.select(
date(Tables.DELIVERY.DELIVERY_TIME.toString()),
count()
)
.from(Tables.DELIVERY)
.groupBy(date(Tables.DELIVERY.DELIVERY_TIME.toString()))
.fetch()
谁能帮我用 jooq 写这个查询
您正在使用 Object.toString()
method, which is available on all Java objects for debugging purposes. In jOOQ, you're going to get a string representation of your column expression. There's no point in doing that in your case. Just use the DSL.cast()
方法,就像您使用 SQL 一样。
假设通常的静态导入:
import static org.jooq.impl.DSL.*;
import static org.jooq.impl.SQLDataType.*;
import static com.example.Tables.*;
写
jooq.dsl()
.select(cast(DELIVERY.DELIVERY_TIME, DATE), count())
.from(DELIVERY)
.groupBy(cast(DELIVERY.DELIVERY_TIME, DATE))
.fetch();