Skip to content

Instantly share code, notes, and snippets.

@henninb
Last active August 31, 2021 04:33
Show Gist options
  • Save henninb/105c26dead2dbbfd92318ce00af02883 to your computer and use it in GitHub Desktop.
Save henninb/105c26dead2dbbfd92318ce00af02883 to your computer and use it in GitHub Desktop.
Jooq.groovy
Field TOTALS_DEBITS = dslContext.select(DSL.coalesce(DSL.sum(T_TRANSACTION.AMOUNT), 0.0).as("debits"))
.from(T_TRANSACTION)
.where(T_TRANSACTION.ACTIVE_STATUS.eq(true) & T_TRANSACTION.ACCOUNT_TYPE.eq("debit")).asField()
Field TOTALS_CREDITS = dslContext.select(DSL.coalesce(DSL.sum(T_TRANSACTION.AMOUNT), 0.0).as("credits"))
.from(T_TRANSACTION)
.where(T_TRANSACTION.ACTIVE_STATUS.eq(true) & T_TRANSACTION.ACCOUNT_TYPE.eq("credit")).asField()
return dslContext.select((TOTALS_DEBITS - TOTALS_CREDITS).as("totals"))
.fetchOneInto(Summary)
@lukaseder
Copy link

You forgot the FROM clause in at least one of your queries ;-)

@lukaseder
Copy link

Happens to me too, occasionally when writing integration tests, btw 😅

@henninb
Copy link
Author

henninb commented Aug 30, 2021

@lukaseder that was a really good catch on the FROM clause missing. I totally missed that. Thank you.

@henninb
Copy link
Author

henninb commented Aug 30, 2021

@lukaseder I updated my code above and I am still seeing the same error.

org.jooq.exception.DataAccessException: SQL [select (select ("debits" - "credits") as "totals") as "totals"]; ERROR: column "debits" does not exist

what is strange is I can dslContext.select((TOTALS_DEBITS, TOTALS_CREDITS) without issues. Please let me know if you have any other thoughts and thanks again.

@lukaseder
Copy link

Ah, I see. It's because you're aliasing your subqueries using .asField("debits"). That's short for .asField().as("debits"). There's no purpose to this aliasing, so just remove it

@henninb
Copy link
Author

henninb commented Aug 30, 2021

@lukaseder thanks again for your time and assistance.

When I remove the .asField("debits") and .asField("credits"), I am not allowed to subtract the 2 fields because they are of type SelectConditionStep. I assume I want these variables to be of type Field so I can subtract them?

@henninb
Copy link
Author

henninb commented Aug 30, 2021

@lukaseder I got it working with the code above. Thank you so much for walking through my struggles with me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment