在Sequelize.js中的聚合函数中使用case-when

时间:2019-05-30 14:13:51

标签: node.js postgresql sequelize.js

是否可以在模型上构建以下查询,而不是对原始sql使用sequilize.query()

select 
  queue,
  count(*) total,
  sum(case when type = 'Proactive' then 1 else 0 end) proactive,
  sum(case when type = 'Reactive' then 1 else 0 end) reactive
from "OpenIncidents" 
group by queue
order by total DESC;

我对sequelize.fn()的聚合函数感到厌倦,但是在文档中没有发现有关CASE WHEN支持聚合函数的信息。

我当前正在使用原始查询

return sequelize.query(
    `
    SELECT 
      queue, 
      COUNT(*) total, 
      SUM(CASE WHEN type = 'Proactive' THEN 1 ELSE 0 END) proactive, 
      SUM(CASE WHEN type = 'Reactive' THEN 1 ELSE 0 END) reactive 
    FROM "OpenIncidents" 
    GROUP BY queue 
    ORDER BY total DESC;
    `, 
    { type: sequelize.QueryTypes.SELECT })
  .then(queues => res.json(queues))
  .catch(err => res.status(400).json(err));

有什么办法可以直接在Sequelize模型上进行操作,如下所示?

return OpenIncident.findAll({
  attributes:[
    'queue',
    [sequelize.fn('COUNT', sequelize.col('id')), 'total'],
    [sequelize.fn('SUM', CASE_WHEN_STATEMENT, 'proactive'],
    [sequelize.fn('SUM', CASE_WHEN_STATEMENT), 'reactive']
  ],
  group: ['queue'],
  order: [sequelize.fn('COUNT', sequelize.col('id')), 'DESC']
})

1 个答案:

答案 0 :(得分:0)

一种解决方案是使用`Sequelize.literal()',如下所示:

[Sequelize.fn('SUM', Sequelize.literal('CASE WHEN type = 'Proactive' THEN 1 ELSE 0 END')), 'proactive']