【问题标题】:Sum over multiple count field对多个计数字段求和
【发布时间】:2017-09-28 18:48:55
【问题描述】:

我尝试将多个计数字段与 JOOQ 和 MySQL 数据库相加。

目前我的代码如下所示:

int userId = 1;
Field<Object> newField = DSL.select(DSL.count()).from(
                DSL.select(DSL.count())
                        .from(REQUIREMENT)
                        .where(REQUIREMENT.CREATOR_ID.equal(userId))
                        .unionAll(DSL.select(DSL.count())
                                .from(REQUIREMENT) 
                                .where(REQUIREMENT.LEAD_DEVELOPER_ID.equal(userId)))

它总是返回 2 作为 newField。但我想知道有多少次用户是需求的创建者以及需求的主要开发者。

【问题讨论】:

    标签: mysql select aggregate-functions jooq


    【解决方案1】:

    你说“sum over multiple count”,但这不是你在做的。您执行“count 计数”。解决方案当然是这样的:

    // Assuming this to avoid referencing DSL all the time:
    import static org.jooq.impl.DSL.*;
    
     select(sum(field(name("c"), Integer.class)))
    .from(
         select(count().as("c"))
        .from(REQUIREMENT)
        .where(REQUIREMENT.CREATOR_ID.equal(userId))
        .unionAll(
         select(count().as("c"))
        .from(REQUIREMENT) 
        .where(REQUIREMENT.LEAD_DEVELOPER_ID.equal(userId)))
    );
    

    或者,如果您打算将更多这些计数添加到总和中,这可能是一个更快的选择:

     select(sum(choose()
        .when(REQUIREMENT.CREATOR_ID.eq(userId)
            .and(REQUIREMENT.LEAD_DEVELOPER_ID.eq(userId)), inline(2))
        .when(REQUIREMENT.CREATOR_ID.eq(userId), inline(1))
        .when(REQUIREMENT.LEAD_DEVELOPER_ID.eq(userId), inline(1))
        .otherwise(inline(0))
     ))
    .from(REQUIREMENT);
    

    More details about the second technique in this blog post

    【讨论】:

    • 感谢您的帮助和 jOOQ!第一个解决方案得到编译器错误:DSL 中的 sum(org.jooq.Field extends java.lang.Number>) 无法应用于 (org.jooq.Field)。但是您的第二个想法效果很好。谢谢!
    • 感谢您的好话。是啊,你说得对。在那里,我修复了第一个示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    相关资源
    最近更新 更多