Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Best way to select row of a max record in group? #6430

Closed
frogcjn opened this issue Aug 13, 2016 · 6 comments
Closed

Best way to select row of a max record in group? #6430

frogcjn opened this issue Aug 13, 2016 · 6 comments

Comments

@frogcjn
Copy link
Contributor

frogcjn commented Aug 13, 2016

a table has a groupId field, and a value field

How to select the full row record the max value in the group using sequelize?

I can only figure it out with SQL:

SELECT 
    a.*
FROM
    table a
        INNER JOIN
    (SELECT 
        groupId, MAX(value) value
    FROM
        table
    GROUP BY groupId) b ON a.groupId = b.groupId
        AND a.value = b.value
GROUP BY a.groupId

and let sequelize run it.

const results = await sequelize.query(sqlSentence, { model: SiteContent })
@janmeier
Copy link
Member

Currently we only support joins on relations defined in sequelize, and we don't have great subquery support either #2787

@frogcjn
Copy link
Contributor Author

frogcjn commented Aug 15, 2016

OK. Thanks. It's good enough.

@PatrickGeyer
Copy link
Contributor

Any news on this @janmeier, is this still not possible?

@4sagar
Copy link

4sagar commented Nov 5, 2019

I managed to get the required result as below

Model.findAll({
        where: {
          id: { 
            [Sequelize.Op.in]: [Sequelize.literal('SELECT MAX(id) FROM a GROUP BY groupId')]
          }
        },
      });

@7hibault
Copy link

7hibault commented Dec 5, 2019

Still using a little bit of SQL, I think the following should work, using DISTINCT ON (official doc).

  • order by your groupId
  • order by the value on which you check the max
  • select only the first row (the max because it is ordered) for each groupId
const results = await MyModel.findAll({
	attributes: [sequelize.literal('DISTINCT ON ("groupId") "MyModels"."groupId"'), 'value'],
	order: [['groupId', 'DESC'], ['value', 'DESC']]
})

@Salmandabbakuti
Copy link

Salmandabbakuti commented Mar 30, 2021

I managed to get the required result as below

Model.findAll({
        where: {
          id: { 
            [Sequelize.Op.in]: [Sequelize.literal('SELECT MAX(id) FROM a GROUP BY groupId')]
          }
        },
      });

above query returning duplicate values too. is there any workaround to prevent duplicates using above query?
@yosagar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants