简体   繁体   中英

Group by in Sequelize when using a function

I want to group by the values returned by a function, as such:

    let noticesOpened = NoticeOpened.aggregate(
        "id",
        "COUNT", {
            plain: false,
            where: noticeWhere,
            group: [sequelize.fn("date_trunc", "day", sequelize.col("created_at"))],
            order: [
                ["created_at", "ASC"]
            ],
        });
    return noticesOpened;

When I try this query I get:

SequelizeDatabaseError: column "notice_opened_tbl.created_at" must appear in the GROUP BY clause or be used in an aggregate function

Is there a way to do an ascending order on the returned grouped value?

You need to order by the result of the function from the group clause, eg something like:

    let noticesOpened = NoticeOpened.aggregate(
        "id",
        "COUNT", {
            plain: false,
            where: noticeWhere,
            group: [sequelize.fn("date_trunc", "day", sequelize.col("created_at"))],
            order: [
                [sequelize.fn("date_trunc", "day", sequelize.col("created_at")), "ASC"]
            ],
        });
    return noticesOpened;

I think to remember you can use sequelize aliases to make this easier but don't have the syntax to hand.

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