英文:
Jooq: Select count group by
问题
我正在尝试计算我的表中 gp_status 字段的不同可能性。我有一个有效的 SQL 查询,只是不太清楚如何将其转换为 Jooq。
SQL 查询如下:
select i.gp_status, COUNT(i.gp_status)
from ideas_service.idea i
group by i.gp_status
到目前为止,在 JOOQ 中我有以下代码:
var result = dsl.select(IDEA.GP_STATUS,count(),count(IDEA.GP_STATUS))
.from(IDEA)
.groupBy(IDEA.GP_STATUS)
.fetch();
看起来字段已正确返回,但我不知道如何提取它们。我知道可能的 gp_status 值。
因此,我需要以某种方式获取行 where gp_status = x
。
英文:
I am trying to count the different possibilities of the gp_status field in my table. I have an sql query that works, just cant quite figure out how to transcribe it to Jooq.
select i.gp_status, COUNT(i.gp_status)
from ideas_service.idea i
group by i.gp_status
So far in JOOQ i have this
var result = dsl.select(IDEA.GP_STATUS,count(),count(IDEA.GP_STATUS))
.from(IDEA)
.groupBy(IDEA.GP_STATUS)
.fetch();
It looks like the fields comeback correctly, but i cant figure out how to extract them.
I do know what the possible gp_status could be.
So i need to somehow get the row where gp_status = x
答案1
得分: 0
如果您只需要单行数据,那么您应该将该谓词添加到您的查询中,即:
var result = dsl.select(IDEA.GP_STATUS, count())
.from(IDEA)
.where(IDEA.GP_STATUS.eq("x"))
.groupBy(IDEA.GP_STATUS)
.fetchOne();
在这种情况下,您实际上不再需要GROUP BY
子句:
var result = dsl.select(count())
.from(IDEA)
.where(IDEA.GP_STATUS.eq("x"))
.fetchOne();
请注意,在这两种情况下,我都使用了ResultQuery.fetchOne()
,它生成一个Record
,您可以以多种方式提取其中的值,例如:
// 重复来自SELECT子句的列表达式
int count1 = result.get(count());
// 按索引访问列,并再次提供类型信息
// 假设已执行第二个查询
int count2 = result.get(0, int.class);
还有许多其他方法。
如果您需要整个结果集,但只想提取一行数据,那么您可以迭代Result
,它扩展了List
,或者使用Result.intoGroups(IDEA.GP_STATUS).get("x")
或Result
上的任何其他方法来执行类似操作。
英文:
If you only need a single row
If you only need a single row, then you should add that predicate to your query, i.e.
var result = dsl.select(IDEA.GP_STATUS, count())
.from(IDEA)
.where(IDEA.GP_STATUS.eq("x"))
.groupBy(IDEA.GP_STATUS)
.fetchOne();
At which point you don't really need the GROUP BY
clause anymore:
var result = dsl.select(count())
.from(IDEA)
.where(IDEA.GP_STATUS.eq("x"))
.fetchOne();
Note that in both cases, I've used ResultQuery.fetchOne()
, which produces a Record
, from which you can extract the value in many ways, e.g.
// Repeat the column expression from the SELECT clause
int count1 = result.get(count());
// Access columns by index, and redundantly supply the type again
// Assuming the second query was executed
int count2 = result.get(0, int.class);
There are many more ways.
If you need the entire result
If you need the entire result set, but for a specific case, just want to extract one row, then you could iterate the Result
, which extends List
, or use Result.intoGroups(IDEA.GP_STATUS).get("x")
or any other method on Result
to do something similar.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论