简体   繁体   English

Jooq:Select 计数组按

[英]Jooq: Select count group by

I am trying to count the different possibilities of the gp_status field in my table.我正在尝试计算表中 gp_status 字段的不同可能性。 I have an sql query that works, just cant quite figure out how to transcribe it to Jooq.我有一个有效的 sql 查询,只是不知道如何将其转录为 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到目前为止,在 JOOQ 我有这个

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.我确实知道可能的 gp_status 可能是什么。

So i need to somehow get the row where gp_status = x所以我需要以某种方式获得where gp_status = x的行

If you only need a single row如果你只需要一行

If you only need a single row, then you should add that predicate to your query, ie如果您只需要一行,那么您应该将该谓词添加到您的查询中,即

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:此时您不再需要GROUP BY子句:

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, eg请注意,在这两种情况下,我都使用ResultQuery.fetchOne() ,它产生一个Record ,您可以通过多种方式从中提取值,例如

// 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.如果您需要整个结果集,但对于特定情况,只想提取一行,那么您可以迭代扩展ListResult ,或使用Result.intoGroups(IDEA.GP_STATUS).get("x")Result上的任何其他方法来做类似的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM