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

qni6mghb  于 2022-12-26  发布在  Node.js
关注(0)|答案(2)|浏览(157)

是否可以在模型上构建下面的查询,而不是对原始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']
})
xpszyzbs

xpszyzbs1#

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

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

m0rkklqb2#

如果您遇到解析问题,以下内容应在2022年12月的Sequelize版本中起作用。

[sequelize.fn('SUM', sequelize.literal("CASE WHEN status = 'PENDING' THEN 1 ELSE 0 END")), 'pending_count'],

相关问题