SQL求和满足条件的数量并与其他列进行比较
我想检查三列是否满足某个条件。接下来,我想对这三个布尔值求和,并检查它们是否与第四列中的值相同。
SELECT SUM(CASE WHEN column1 LIKE 'D%' THEN 1 ELSE 0 END) AS bool1
SUM(CASE WHEN column2 LIKE 'D%' THEN 1 ELSE 0 END) AS bool2
SUM(CASE WHEN column3 LIKE 'D%' THEN 1 ELSE 0 END) AS bool3
FROM table
WHERE bool1 + bool2 + bool3 = column4
然而,这会产生错误。我应该如何更改查询?
I want to check for three columns if a certain condition holds. Next, I want to sum these three booleans and check whether they are the same as a value in a fourth column.
SELECT SUM(CASE WHEN column1 LIKE 'D%' THEN 1 ELSE 0 END) AS bool1
SUM(CASE WHEN column2 LIKE 'D%' THEN 1 ELSE 0 END) AS bool2
SUM(CASE WHEN column3 LIKE 'D%' THEN 1 ELSE 0 END) AS bool3
FROM table
WHERE bool1 + bool2 + bool3 = column4
This gives an error however. How should I change the query?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
聚合函数
SUM()
对一列的所有值进行运算,因此将其与另一列的特定值进行比较是没有意义的。我怀疑您想要这样的东西:
Each布尔表达式
columnX LIKE 'D%'
的计算结果为0
(对于false
)和1
(对于true)
.如果有列中的
null
更改为:Aggregate function
SUM()
operates on all values of a column, so it does not make sense to compare it to a specific value of another column.I suspect that you want something like this:
Each of the boolean expressions
columnX LIKE 'D%'
evaluates to0
forfalse
and1
fortrue
.If there are
null
s in the columns change to: