SQL 查询根据条件计算行数?不断收到我的计数逻辑的语法错误
SQL query to count rows based on condition? Keep getting syntax error for my count logic
select sum(bookID) as totalbooks, count(bookstatus = R) as returnedbooks
from library with (nolock)
where
librarylocation = 'Chesterfield'
--and bookstatus = R
所以我希望我的查询 return 一列总共有多少本书,但是 return 一列有多少本书。我正在使用 count 也应用条件,但我收到错误消息:
Incorrect syntax near ')'.
无论如何要实现这个?
这里是语法错误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
select sum(bookID) as totalbooks, count(bookstatus = R) as returnedbooks
from library with (nolock)
where
librarylocation = 'Chesterfield'
--and bookstatus = R
所以我希望我的查询 return 一列总共有多少本书,但是 return 一列有多少本书。我正在使用 count 也应用条件,但我收到错误消息:
Incorrect syntax near ')'.
无论如何要实现这个?
这里是语法错误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