在where子句中使用多个AND运算符

时间:2017-12-11 07:45:52

标签: sql sql-server

我有多个条件,我想检查数据库列,我可以这样做吗?

(SELECT COUNT(*) FROM PscData where SETTLEMENT_ID = T.SETTLEMENT_ID AND NO_OF_BUFFALO >= 1
            AND NO_OF_COW >= 1
            AND NO_OF_GOAT >= 1
            AND NO_OF_SHEEP >= 1
            ) as At_Least_1_Buffalo_Bullock_Cow_Goat_Sheep

它没有给我准确的答案。 我想从我的数据中得到总计数,其中至少有1头牛,山羊,绵羊或水牛。

3 个答案:

答案 0 :(得分:3)

OR子句

中需要AND而不是WHERE
SELECT COUNT(*) FROM PscData where SETTLEMENT_ID  = T.SETTLEMENT_ID AND (
        NO_OF_BUFFALO >= 1
            OR NO_OF_COW >= 1
            OR NO_OF_GOAT >= 1
            OR NO_OF_SHEEP >= 1)

答案 1 :(得分:0)

@Eralper有一种方法,但逻辑上我认为这描述了你想要的更好

(SELECT COUNT(*) FROM PscData where SETTLEMENT_ID = T.SETTLEMENT_ID AND  (NO_OF_BUFFALO >= 1
            OR NO_OF_COW >= 1
            OR NO_OF_GOAT >= 1
            OR NO_OF_SHEEP >= 1
            ) ) as At_Least_1_Buffalo_Bullock_Cow_Goat_Sheep

请注意,OR而不是AND用于单独的条件。

答案 2 :(得分:-1)

我认为你要找的是查询

SELECT COUNT(*) 
FROM PscData 
where 
SETTLEMENT_ID = T.SETTLEMENT_ID AND 
( NO_OF_BUFFALO + NO_OF_COW + NO_OF_GOAT + NO_OF_SHEEP) >= 1
--SUM( NO_OF_BUFFALO + NO_OF_COW + NO_OF_GOAT + NO_OF_SHEEP) >= 1

很抱歉打字错误,我们在这里不需要SUM()函数,我对此进行了评论。