Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
Having trouble finding distinct records using sequelize

let's assume i have a table with records like [{fruit : apple, colour : green, price : 100 },{fruit : apple, colour : red, price : 75},{fruit : banana, colour : yellow, price : 50}].

What would be the sequelize command if i wanted to fetch unique fruits, but i want to fetch only the colour field along with it, and i want only 1 occurance of a fruit... So for this table, i want my output to be [{fruit : apple, colour : green},{fruit : banana, colour : yellow}]

This is what I tried :

fruitVendor.findAndCountAll({
attributes:[[Sequelize.fn('DISTINCT', Sequelize.col('fruit')),'FRUIT'],['colour','COLOUR']]
})

But i got [{fruit : apple, colour : green},{fruit : apple, colour : red},{fruit : banana, colour : yellow}]

And then i removed colour as one of the attributes just to check if distinct was working fine:

fruitVendor.findAndCountAll({
attributes:[[Sequelize.fn('DISTINCT', Sequelize.col('fruit')),'FRUIT']
})

And i got [{fruit : apple},{fruit : banana}]

So even if i mention distinct with one specific attribute, it applied it to the others as well?

Can anyone help me get [{fruit : apple, colour : green},{fruit : banana, colour : yellow}]

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

This is how SELECT DISTINCT works with SQL. It evaluates all the combinations of the columns you chose to select from.

If it didn't do it this way, how would it know that you wanted {fruit: apple, color: green} instead of {fruit: apple, color: red}?

about 4 years ago · Juan Pablo Isaza Report

0

If you are okay with any color, you can try this.

fruitVendor.findAndCountAll({
    attributes: [['fruit','FRUIT'], [Sequelize.fn('MIN', Sequelize.col('colour')), 'COLOUR']], // Or MAX
    group: 'fruit'
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!