Skip to content

Unable to exclude primaryKey while performing an Aggregation (sum) with Join #3920

Closed

Description

@cludden

I am attempting to perform an aggregation (sum) with a join, and the closest I've gotten is with the below:

        Balance.findAll({
            attributes: [
                [app.sequelize.fn('sum', app.sequelize.col('usdAmount')), 'sum']
            ],
            where: {
                date: {
                    $between: ['2015-01-01', '2015-12-31']
                },
                ledgerId: '04'
            },
            include: [
                {
                    model: Accounts,
                    attributes: [],
                    where: {
                        'ebitdaDesc': 'EBITDA'
                    }
                }
            ]
        }).then(function(result) {
            console.log(result);
            res.status(200).send();
        }, function(err) {
            console.log(err);
            res.status(500).send();
        });

which generates the following query:

'SELECT [Balances].[id], sum([usdAmount]) AS [sum] FROM [GL].[Balances] AS [Balances] INNER JOIN [GL].[Accounts] AS [Account] ON [Balances].[accountId] = [Account].[id] AND [Account].[ebitdaDesc] = \'EBITDA\' WHERE [Balances].[date] BETWEEN \'2015-01-01\' AND \'2015-12-31\' AND [Balances].[ledgerId] = \'04\';'

and the following error:

'Column \'GL.Balances.id\' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.'

The query executes as expected without including the "[Balances].[id]" in the select statement, but I have not determined how to exclude this.

Any help would be greatly appreciated!

Activity

  1. cludden commented on Jun 11, 2015

    @cludden
    Author

    As a follow up,
    I was able to correct the query by commenting out the following code:

    /lib/model.js#1181
    
            if (options.attributes) {
              if (options.attributes.indexOf(this.primaryKeyAttribute) === -1) {
                options.originalAttributes = options.attributes;
                options.attributes = [this.primaryKeyAttribute].concat(options.attributes);
              }
            }
    

    Are there any implications in doing this that I'm unaware of (besides having to manually include the primaryKey when I need it)?

  2. mickhansen commented on Jun 12, 2015

    @mickhansen
    Contributor

    We add the primary key attribute because we need to be able to run deduplication logic.

  3. mickhansen commented on Jun 12, 2015

    @mickhansen
    Contributor

    Not quite sure what would be the best solution here.

  4. pimterry commented on Jun 24, 2015

    @pimterry
    Contributor

    I'm also hitting this exact problem. The core of the issue does seem to be the include. If instead I have attributes set to SUM over a column of the main model (not the included one) and don't set 'include' at all then it the primary key doesn't get added, the field is summed happily, and everything is fine. It'd be nice to get that same behaviour when summing over include'd models.

    Is the deduplication needed if the query has 'raw' set to true? Would it be possible to not include the primary key in that case?

    Any other ideas? At the moment this is a very useful operation (same as #2427 I think) which doesn't seem to be possible in Sequelize at all.

  5. mickhansen commented on Jun 24, 2015

    @mickhansen
    Contributor

    @pimterry If raw the deduplication logic would not be run no, so the primary key wouldn't be needed in that case.

    If you are only doing filtering on the include and you don't need it's attributes include.attributes = []should work.

  6. pimterry commented on Jun 24, 2015

    @pimterry
    Contributor

    Ah, that's great, ok thanks.

    I'm afraid putting the attributes on the include doesn't work. As soon as you have any include property set at all, the primary key for the outer model is added to the attributes, and that means you can't aggregate over that model, because of

    if (options.attributes) {
    (which pretty exactly says: 'if include set, and attributes doesn't include the primary key, add the primary key as an attribute').

    Tangentially, it also wouldn't work for me because I'm not just filtering over the include, I'm aggregating the elements from it. I want to end up with something like:

    SELECT SUM(pw.sales) AS aggregatedSales
    FROM Products as p
    INNER JOIN ProductWeeks pw on p.id = pw.productId
    WHERE p.name = 'cheese';

    My best current attempt is:

    model.Product.findAll({
        attributes: [],
        include: {
            model: model.ProductWeek,
            attributes: [[db.fn('SUM', db.col('ProductWeek.sales')), 'aggregatedSales']]
        },
        where: { name: 'cheese' }
        raw: true
    });

    But this results in:

    SELECT [Product].[id],
    [ProductWeeks].[id] AS [ProductWeeks.id],
    SUM([ProductWeeks].[sales]) AS ProductWeeks.aggregatedSales]
    FROM [Products] AS [Product]
    LEFT OUTER JOIN [ProductWeeks] AS [ProductWeeks]
    ON [Product].[id] = [ProductWeeks].[ProductId]
    WHERE [Product].[name] = 'cheese';

    Would you be happy for me to put in a PR to disable this behaviour (adding the primary key to attributes when explicitly not included) when 'raw' is set? I'll test in a moment, but I looks likely that this would solve this issue neatly for me.

  7. pimterry commented on Jun 24, 2015

    @pimterry
    Contributor

    In the meantime I've fixed this for my project with:

    function resetAttributes(options) {
        if (options.originalAttributes !== undefined) {
            options.attributes = options.originalAttributes;
            if (options.include) {
                options.include.forEach(function (include) {
                    resetAttributes(include);
                });
            }
        }
    }
    
    var db = new Sequelize(connectionString, {
        hooks: {
            "beforeFindAfterOptions": function (options) {
                if (options.raw) {
                    resetAttributes(options);
                }
            }
        }
    });

    Now works fine for my case (although only with findAll - findOne or findById for some reason add Product.* to the SELECT list again after the 'beforeFindAfterOptions' hook - might investigate this later separately).

  8. mickhansen commented on Jun 24, 2015

    @mickhansen
    Contributor

    Yeah we'd welcome a PR with something like that, remember to add a test :)

  9. pimterry commented on Jul 2, 2015

    @pimterry
    Contributor

    I've created a PR for this (see above), that's just waiting to get looked at now. This fixes this issue for me (as long as you set raw: true).

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions