用于计算多列行的 Sequelize 查询

Sequelize Query for counting rows of more than one column

我有这个代码

     await   expense.model.findAll({
  attributes: { 
    include: [[instance.sequelize.fn("COUNT", instance.sequelize.col('expense_category')), "expenseCount"]] ,  
  },
  where:[{uuid: user.uuid, expense_category: "Home"}]
  }).then(data => {
  res.send(data)
})

相当于

select COUNT(expense_category) as expenseCountfrom customers where expense_category= "Home" AND uuid = user.uuid

问题是,由于我要使用 Chart.js 的计数,我需要再次查询,因为我还有 3 个其他 expense_category,即:MiscellaneousFood and BeverageTransportation。有没有一种方法可以使我上面的代码更有效率,而不必每个 expense_category?

单独查询

我假设您已经为 category.You 使用了枚举,可以使用 findall 中的组并删除 where 子句中费用类别的其他条件,例如:

    await   expense.model.findAll({
  where:{uuid: user.uuid},
  group:['expense_category'],
  attributes: { 
    'expense_category'
    [instance.sequelize.fn("COUNT", instance.sequelize.col('expense_category')), "expenseCount"]  
  }
  }).then(data => {
  res.send(data)
})

你会得到这样的回复

[
 {
   'expense_catogory':"Home",
   'expenseCount': 10
 },
{
   'expense_catogory':"Miscellaneous",
   'expenseCount': 2
 },
{
   'expense_catogory':"Food and Beverage",
   'expenseCount': 7
 },
{
   'expense_catogory':"Transportation",
   'expenseCount': 3
 }
]