我的查询应该计算上个月内特定客户被添加到表中的次数。如果仅使用:
WHERE Return_Table.DateAdded >= DATEADD(month, -1, GETDATE())
然后我在上个月获得了所有的“ CustomerID”和“ TimesReturned”,这似乎是有效的,但是当我使用“ AND”和“ OR”搜索特定条目时,我得到的结果如下所示,但是结果不再计算上个月内的条目。
实际上,当我在搜索中包含或多或少的特定客户时,“ TimesReturned”值将发生变化。因此,如果我先搜索“ cust1-4”,然后搜索“ cust1-2”,TimesReturned计数将发生1和2的变化。
MyQuery:
SELECT TOP 20 Return_Table.Customer_ID, COUNT(*) AS TimesReturned
FROM Return_Table
WHERE Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) AND
Return_Table.Customer_ID ='cust1' OR
Return_Table.Customer_ID ='cust2' OR
Return_Table.Customer_ID ='cust3' OR
Return_Table.Customer_ID ='cust4'
GROUP BY Return_Table.Customer_ID
ORDER BY TimesReturned DESC
结果:
Customer_ID TimesReturned
Cust1 24
Cust2 14
Cust3 4
Cust4 2
..... ....
尽管此结果的格式是正确的,但我的查询必须有问题才能使值更改为这样。
答案 0 :(得分:4)
仔细查看WHERE
子句:
WHERE Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) AND
Return_Table.Customer_ID ='cust1' OR
Return_Table.Customer_ID ='cust2' OR
Return_Table.Customer_ID ='cust3' OR
Return_Table.Customer_ID ='cust4'
它将匹配以下行:
等等。这说明了为什么原始计数(没有客户ID过滤器)的计数增加。添加括号,您应该会很好:
WHERE
Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) AND
(
Return_Table.Customer_ID ='cust1' OR
Return_Table.Customer_ID ='cust2' OR
Return_Table.Customer_ID ='cust3' OR
Return_Table.Customer_ID ='cust4'
)
PS:以上内容与以下内容相同:
WHERE
Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) AND Return_Table.Customer_ID ='cust1' OR
Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) AND Return_Table.Customer_ID ='cust2' OR
Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) AND Return_Table.Customer_ID ='cust3' OR
Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) AND Return_Table.Customer_ID ='cust4'
答案 1 :(得分:2)
使用in运算符代替多个OR:
SELECT TOP 20 Return_Table.Customer_ID,
COUNT(*) AS TimesReturned
FROM Return_Table
WHERE Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) AND
Return_Table.Customer_ID in ('cust1' ,'cust2' 'cust3','cust4')
GROUP BY Return_Table.Customer_ID
ORDER BY TimesReturned DESC
答案 2 :(得分:1)
您需要使用括号,当您将or
与多个and
一起使用时,最好使用括号,否则根据运算符优先级来处理结果
SELECT TOP 20 Return_Table.Customer_ID,
COUNT(*) AS TimesReturned
FROM Return_Table
WHERE Return_Table.DateAdded >= DATEADD(month, -1, GETDATE()) AND
(Return_Table.Customer_ID ='cust1' OR
Return_Table.Customer_ID ='cust2' OR
Return_Table.Customer_ID ='cust3' OR
Return_Table.Customer_ID ='cust4'
)
GROUP BY Return_Table.Customer_ID
ORDER BY TimesReturned DESC