【问题标题】:SQL query to count rows based on condition? Keep getting syntax error for my count logicSQL查询根据条件计算行数?我的计数逻辑不断出现语法错误
【发布时间】:2021-10-10 04:02:48
【问题描述】:
select sum(bookID) as totalbooks, count(bookstatus = R) as returnedbooks
from library with (nolock)
where 
   librarylocation = 'Chesterfield'
   --and bookstatus = R

所以我希望我的查询以一列的形式返回总共多少本书,但以一列的形式返回多少本书。我正在使用 count 也应用条件,但我收到错误消息:

')' 附近的语法不正确。

无论如何要做到这一点?

【问题讨论】:

  • 停止使用nolock 溅出你的代码

标签: sql sql-server tsql count sum


【解决方案1】:

这里是语法错误count(bookstatus = R)

你可以像下面这样转换它

select sum(bookID) as totalbooks, SUM(CASE WHEN bookstatus = R THEN 1 ELSE 0 END) as returnedbooks
from library with (nolock)
where librarylocation = 'Chesterfield'
--and bookstatus = R

【讨论】:

  • ... SUM(bookID) as totalbooks 或 ... COUNT(bookID) as totalbooks?
  • SUM(1) 等价于COUNT,两者都有效
猜你喜欢
  • 2019-06-11
  • 1970-01-01
  • 1970-01-01
  • 2019-05-29
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
相关资源
最近更新 更多