I have table with value
id country 1 india 2 usa 3 india
I need to find the distinct values from the country column using sequelize.js
here my sample code...
Project.findAll({ attributes: ['country'], distinct: true }).then(function(country) { ............... });
Is there any way to find the distict values
You can use the the group option, however to avoid the MySQL error incompatible with sql_mode=only_full_group_by you must apply the MAX function to others attributes. Show activity on this post. You can use raw queries to get the result or sequelize. fn() .
count , you can just add any kind of aggregate function arguments supported by MYSQL to your options object. The following code will give you the amount of different values in MyModel 's someColumn : MyModel. count({distinct: 'someColumn', where: {...}}) .
To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.
You can specify distinct for one or more attributes using Sequelize.fn
Project.findAll({ attributes: [ // specify an array where the first element is the SQL function and the second is the alias [Sequelize.fn('DISTINCT', Sequelize.col('country')) ,'country'], // specify any additional columns, e.g. country_code // 'country_code' ] }).then(function(country) { })
I ended up using grouping like this:
Project.findAll({ attributes: ['country'], group: ['country'] }).then(projects => projects.map(project => project.country) );
It results into distinct models you can nicely iterate.
Link in previous answer helped little bit: https://github.com/sequelize/sequelize/issues/2996#issuecomment-141424712
This works well too, but generating response with DISTINCT as column name:
Project.aggregate('country', 'DISTINCT', { plain: false }) .then(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With