我在将SQL查询转换为JOOQ时遇到了一些问题。因此,join子句中的别名sugActive是未知的。可能有更好的方式编写此代码。因此,我仍然不知道出了什么问题。我感谢任何提示,谢谢。
1. The SQL query:
select
count(campId) as 'campCount',
count(case when targetTest != 0 then campId else null end) as 'targetTestSet',
count(case when targetTest = 0 then campId else null end) as 'targetTestNotSet',
coalesce(sum(sugActive), 0) as 'sugActive',
coalesce(sum(sugApproved), 0) as 'sugApproved',
from (
select
c.venId,
c.name,
s.*
from campTable c
join (select s.campId,
count(case when s.status = 'ACTIVE'
then id end) as 'sugActive',
count(case when s.status = 'APPROVED'
then id end) as 'sugApproved',
from sugTable s
group by s.campId
) s on c.campId = s.campId
where c.state = 'enabled'
) a;
返回
2. The JOOQ query:
Field<Integer> sugActive = igDb
.select(
count(when(
sugTable.status.eq("ACTIVE"), sugTable.campId)
.as("sugActive")))
.from(sugTable).asField("sugActive");
Field<Integer> sugApproved = igDb
.select(
count(when(
sugTable.status.eq("APPROVED"), sugTable.campId)
.as("sugApproved")))
.from(sugTable).asField("sugApproved");
IgOrgSumRecord result = igDb
.select(
count(campTable.venId).as("venIdCount"),
count(sugTable.campId).as("campCount"),
count(when(
campTable.targetTest.notEqual(BigDecimal.ZERO), sugTable.campId
).otherwise("")).as("targetTestSet"),
count(when(
campTable.targetTest.eq(BigDecimal.ZERO), sugTable.campId
).otherwise("")).as("targetTestNotSet"),
coalesce(sum(sugActive)).as("sugActive"),
coalesce(sum(sugApproved)).as("sugApproved"))
.from(select(
campTable.venId,
campTable.name,
sugTable.asterisk()
)
.from(campTable.as("c"))
.join(
select(
sugTable.campId,
count(when(
sugTable.status.eq("ACTIVE"), sugTable.campId)
.as("sugActive")),
count(when(
sugTable.status.eq("APPROVED"), sugTable.campId)
.as("sugApproved"))
)
.from(sugTable)
.groupBy(sugTable.campId)
)
.on(campTable.campId.eq(sugTable.campId))
.where(campTable.state.eq("enabled"))
)
.fetchOneInto(IgOrgSumRecord.class);
返回
我得到的错误:“字段列表”中的未知列“ sugActive”。
问题是这样:
Field<Integer> sugActive = igDb
.select(
count(when(
sugTable.status.eq("ACTIVE"), sugTable.campId)
.as("sugActive")))
.from(sugTable).asField("sugActive");
这不仅是列表达式,还是别名声明(或引用)。然后,当您实际要使用表达式时,您将使用别名引用,对其重新进行别名处理:
coalesce(sum(sugActive)).as("sugActive"),
相反,像这样声明您的sugActive
变量:
Field<Integer> sugActive = field(igDb
.select(
count(when(
sugTable.status.eq("ACTIVE"), sugTable.campId)
.as("sugActive")))
.from(sugTable));