简体   繁体   中英

How to write this query in jooq

select sum(x.amt) from (select amount as amt from user_transactions where TransactionTimeStamp > '2022-03-09') as x

I am not able to convert this sql query to jooq query. Please help

Creating derived tables

You can create derived tables like this:

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

Table<?> x = table(
    select(USER_TRANSACTIONS.AMOUNT)
    .from(USER_TRANSACTIONS)
    .where(USER_TRANSACTIONS.TRANSACTIONTIMESTAMP.gt(
        LocalDate.parse("2022-03-09")
    ))
).as("x");

And then use it like this:

ctx.select(sum(x.field(USER_TRANSACTIONS.AMOUNT)))
   .from(x)
   .fetch();

Alternative using FILTER

jOOQ supports the standard SQL FILTER clause, and can emulate it also for SQL Server:

ctx.select(sum(USER_TRANSACTIONS.AMOUNT).filterWhere(
       USER_TRANSACTIONS.TRANSACTIONTIMESTAMP.gt(LocalDate.parse("2022-03-09"))
   ))
   .from(USER_TRANSACTIONS)
   .fetch();

This is especially useful if you're aggregating several things in a single query , eg with different filters

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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