SQL计数记录与计数和拥有

时间:2011-02-06 10:44:00

标签: sql count having

我遇到的问题是我认为是一个简单的查询来计算记录:

SELECT req_ownerid, count(req_status_lender) AS total6 
FROM bor_requests
WHERE (req_status_lender = 0 AND req_status_borrower = 0) OR 
      (req_status_lender = 1 AND req_status_borrower = 1)
GROUP BY req_ownerid 
HAVING req_ownerid = 70

我认为这会计算所有记录(req_status_lender = 0 AND req_status_borrower = 0)和(req_status_lender = 1 AND req_status_borrower = 1),然后给我总数,但它只给我总数(req_status_lender = 0) AND req_status_borrower = 0)或(req_status_lender = 1 AND req_status_borrower = 1)。

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:2)

您应该仅使用HAVING子句来限制上面查询中汇总的内容 - 例如如果您要选择SUM(....)COUNT(...)大于5的所有行,那么您将使用HAVING SUM(...) > 5

你在这里做的是一个标准的WHERE条款 - 把它添加到那里!

SELECT req_ownerid, count(req_status_lender) AS total6 
FROM bor_requests
WHERE req_ownerid = 70
      AND ((req_status_lender = 0 AND req_status_borrower = 0) OR 
           (req_status_lender = 1 AND req_status_borrower = 1))
GROUP BY req_ownerid