Saeed D. :
How do I write the following SQL in JOOQ?
SELECT COUNT(*) as total,
SUM(CASE WHEN (in_kind OR goods) THEN 1 ELSE 0 END) AS alt_donation
FROM donation
All the three columns (‘not_found’, ‘in_kind’ and ‘goods’) are boolean.
I have looked at other related questions and JOOQ CASE Documentation and can make the following sql work in JOOQ.
SELECT COUNT(*) AS total,
SUM(CASE WHEN (not_found) THEN 0 ELSE 1 END) AS alt_donation
FROM donation
The JOOQ version runs correctly for this example:
val query = dslContext
.select(DSL.count().`as`("donations"),
DSL.sum(DSL.choose(DONATION.NOT_FOUND).`when`(true, 0).otherwise(1)).`as`("altdonation"))
.from(DONATION)
I need to use the earlier sql statement that uses an 'or' in CASE.
Lukas Eder :
You could probably use the FILTER (WHERE ..)
clause, which is supported by jOOQ and emulated in SQL dialects that don't natively support it, in a similar way as yours:
In SQL
SELECT COUNT(*) as total,
COUNT(*) FILTER (WHERE in_kind OR goods) AS alt_donation
FROM donation
In jOOQ
ctx.select(count().`as`("donations"),
count().filterWhere(condition(DONATION.IN_KIND)
.or(condition(DONATION.GOODS))).`as`("alt_donation"))
.from(DONATION)
.fetch();
Notice I'm turning a Field<Boolean>
into a Condition
using DSL.condition(Field<Boolean>)
, which is probably the API you were looking for