I have a query that is gathering information based on a set of conditions. Basically I want to know if a location has paid out more than $50 for the day OR the comment section has the word "filter" in it...
My query is:
SELECT Store_Id, Paid_Out_Amount, Paid_Out_Comment, Paid_Out_Datetime, Update_UserName, Till_Number
FROM Paid_Out_Tb
WHERE (Store_Id = 1929) AND (Paid_Out_Datetime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()) - 1, 0)) AND (Paid_Out_Datetime < DATEADD(day, DATEDIFF(day, 0,
GETDATE()), 0)) AND (Paid_Out_Amount > 50) OR
(Paid_Out_Comment LIKE N'%' + 'Filter' + '%')
The problem is It returns 460 results and should only return 2.
Example - Two Conditions in the WHERE Clause (AND Condition)You can use the AND condition in the WHERE clause to specify more than 1 condition that must be met for the record to be selected.
Description. The SQL AND condition and OR condition can be combined to test for multiple conditions in a SELECT, INSERT, UPDATE, or DELETE statement. When combining these conditions, it is important to use parentheses so that the database knows what order to evaluate each condition.
The WHERE clause can be combined with AND , OR , and NOT operators.
You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition.
AND
takes precedence over OR
. You need to group your conditions if you want to control the precedence. Try this:
SELECT Store_Id, Paid_Out_Amount, Paid_Out_Comment, Paid_Out_Datetime, Update_UserName, Till_Number
FROM Paid_Out_Tb
WHERE (Store_Id = 1929) AND (Paid_Out_Datetime >= DATEADD(day, DATEDIFF(day, 0, GETDATE()) - 1, 0)) AND (Paid_Out_Datetime < DATEADD(day, DATEDIFF(day, 0,
GETDATE()), 0)) AND ( (Paid_Out_Amount > 50) OR
(Paid_Out_Comment LIKE N'%' + 'Filter' + '%') )
You need to wrap your Paid_Out_Amoutn and Paid_Out_Comment criteria in a second set of parentheses:
SELECT Store_Id, Paid_Out_Amount, Paid_Out_Comment, Paid_Out_Datetime,
Update_UserName, Till_Number
FROM Paid_Out_Tb
WHERE (Store_Id = 1929) AND (Paid_Out_Datetime >=
DATEADD(day, DATEDIFF(day, 0, GETDATE()) - 1, 0)) AND
(Paid_Out_Datetime < DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)) AND
(
(Paid_Out_Amount > 50) OR (Paid_Out_Comment LIKE N'%' + 'Filter' + '%')
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With