jooq查询用于具有分析功能的sql查询

yrwegjxp  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(349)

我有sql查询,比如

select *
from (
   select s.*, max(year) over () max_year
   from Transaction s
   where s.Account_Number     = '4234242234'
     and s.month in (0,1)) o
where o.year=o.max_year;

我需要用jooq写,任何帮助。我试过下面的

dslContext.select(Transaction.BANK,
                    Transaction.ACCOUNT,
                    Transaction.AMOUNT,
                    max(Transaction.YEAR).over())
            .from(Transaction)
            .where(Transaction.BANK.eq(bank))
            .and(Transaction.MONTH.in((byte) 0, (byte) 1))
            .fetchInto(Transaction.class);

另外,有没有办法避免在select中列出所有列。而不是

select(Transaction.BANK,
       Transaction.ACCOUNT,
       Transaction.AMOUNT,
       max(Transaction.YEAR).over())

像这样的

select(Transaction.*,
       max(Transaction.YEAR).over())
lymnna71

lymnna711#

派生表可以这样构造:

// Assuming this static import, as always:
import static org.jooq.impl.DSL.*;

// Create aliased column expression for later reuse
Field<Integer> maxYear = max(Transaction.YEAR).over().as("max_year");

// Create derived table
Table<?> o = select(Transaction.asterisk(), maxYear)
            .from(Transaction)
            .where(Transaction.BANK.eq(bank))
            .and(Transaction.MONTH.in((byte) 0, (byte) 1))
            .asTable("o");

// Use derived table and dereference fields from it using Table.field(Field)
ctx.select()
   .from(o)
   .where(o.field(Transaction.YEAR).eq(o.field(maxYear)))
   .fetch();

另外,有没有办法避免在select中列出所有列
你在找什么 Table.asterisk() 在sql中生成星号,或 Table.fields() 从生成的代码生成所有字段。

相关问题