I have a Score table which belongs to the users table user can have many Score I want query all user with company id and want to total all their scores in original_score
below is Sequelize query
let data = await sequelize.Users.findAll({ where: { company_id: req.body.company_id }, attributes: [ [db.Sequelize.fn('sum', db.Sequelize.col('Scores.original_score')), 'original_score'] ], include: [ { model: sequelize.Score, attributes: [] } ], group: ["Users.id", "Scores.id"], attributes: { exclude: ["token", "game_json"] }, })
Raw Query
SELECT "Users"."id", "Users"."name", "Users"."unique_id", "Users"."email", "Users"."department", "Users"."region", "Users"."device_id", "Users"."age", "Users"."gender", "Users"."education", "Users"."country_id", "Users"."company_id", "Users"."licence_id", "Users"."batch_id", "Users"."level_access", "Users"."password", "Users"."role", "Users"."signup_token", "Users"."user_type", "Users"."is_active", "Users"."is_tutorial_finshed", "Users"."volume", "Users"."progress", "Users"."last_chapter", "Users"."createdAt", "Users"."updatedAt" FROM "Users" AS "Users" LEFT OUTER JOIN "Score" AS "Scores" ON "Users"."id" = "Scores"."user_id" WHERE "Users"."company_id" = 2 GROUP BY "Users"."id", "Scores"."id";
I am getting data like below from above query but it doesn't include original_score
{ "id": 4, "name": "userUpdate", "unique_id": "61884ff1-466f-429e-a359-9879073054fc", "role": "USER", "signup_token": null, "user_type": "user", "is_active": true, "is_tutorial_finshed": null, "volume": null, "progress": null, "last_chapter": null, "createdAt": "2021-03-23T14:05:53.963Z", "updatedAt": "2021-03-25T16:34:01.840Z" },
https://stackoverflow.com/questions/66807202/using-group-by-and-joins-in-sequelize-not-getting-sum-original-score-column-of-i March 26, 2021 at 04:32AM
没有评论:
发表评论