连续减计数

时间:2018-09-19 02:42:15

标签: mysql sequelize.js

我试图通过从所有具有真实记录中减去所有具有虚假记录来获得计数。我无法在Sequelize中复制此类内容,但可以在原始查询中创建它:

SELECT (SELECT Count(id) 
    FROM   votes 
    WHERE  up = true 
           AND id = 1) - (SELECT Count(id) 
                                   FROM   votes 
                                   WHERE  up = false 
                                          AND id = 1) AS votes 

基于文档,我看不到执行此操作的方法。有什么我想念的吗?

1 个答案:

答案 0 :(得分:1)

这对于您的js库来说可能更简单

select count(case when up = true then 1 end) - count(case when up = false then 1 end)
from votes
where id = 1

那么先前的答案应该对我有帮助: https://stackoverflow.com/a/47397320/2067753

请注意,count()函数将忽略空值,但是使用sum()而不是count可以得到相同的最终结果:

select sum(case when up = true then 1 else 0 end) - sum(case when up = false then 1 else 0 end)
from votes
where id = 1

使用group by

select id, count(case when up = true then 1 end) - count(case when up = false then 1 end)
from votes
where id = 1
group by id