[英]SQL Server - Order of Operations difficulty
Trying to figure out how to order this properly to get the expected result.试图弄清楚如何正确订购以获得预期的结果。 What I'm looking for is A to be true, and any of B, C, or D to be true also.
我正在寻找的是 A 为真,而 B、C 或 D 中的任何一个也为真。 Starting_Date and Ending_Date are defined earlier in the code.
Starting_Date 和 Ending_Date 在代码的前面定义。
Declare @Starting_Date date = '2019-01-01'
Declare @Ending_Date date = '2019-01-31'
Select x
From y
Where REPORTING_UNIT = '36B11' --A
AND ((Closing_Date BETWEEN @Starting_Date AND @Ending_Date) --B Closing date is between report date range (eg: episode already open before period)
OR (Opening_Date BETWEEN @Starting_Date AND @Ending_Date) --C Opening date is between report date range (eg: episode was opened at some point during the period)
OR (Reverse_Opening_Date BETWEEN @Starting_Date AND @Ending_Date)) --D Reverse opening date is between report date range (eg: episode was closed at some point, then reopened during the period)
Expected results:预期成绩:
Year of 1858 is the database's way of say "it isn't closed". 1858 年是数据库表示“它没有关闭”的方式。 So in this example, all of these would be included except for line #14, which was closed prior to our defined ending date.
所以在这个例子中,除了第 14 行之外,所有这些都将包括在内,该行在我们定义的结束日期之前关闭。 Lines 5 & 6 would also be included because the episode was open during the period we are evaluating.
第 5 行和第 6 行也将包括在内,因为该剧集在我们评估期间是开放的。
Edit: Added starting and ending date coded in and some expected results.编辑:添加了编码的开始和结束日期以及一些预期结果。
Just keep REPORTING_UNIT = '36B11' AND Closing_Date BETWEEN @Starting_Date AND @Ending_Date
conditions in the WHERE
clause and see the results that you get and then add the OR
conditions one by one and you may get an idea of why this is happening.只需在
WHERE
子句中保留REPORTING_UNIT = '36B11' AND Closing_Date BETWEEN @Starting_Date AND @Ending_Date
条件,然后查看获得的结果,然后逐个添加OR
条件,您可能会了解为什么会发生这种情况。 Also, after a cursory glance at your data above, logically only row 5 should be included.此外,粗略浏览一下您的上述数据后,逻辑上只应包括第 5 行。
BETWEEN
clause will just check the date range and row 5 satisfies that. BETWEEN
子句将只检查日期范围,第 5 行满足这一要求。
The following, which is your code minus the redundant parentheses inside the OR sequence, should work.以下是您的代码减去 OR 序列中的冗余括号,应该可以工作。
Are you confident about the values of @Starting_Date and @Ending_Date?您对@Starting_Date 和@Ending_Date 的值有信心吗?
Select x
From y
Where REPORTING_UNIT = '36B11' --A
AND (Closing_Date BETWEEN @Starting_Date AND @Ending_Date --B Closing date is between report date range (eg: episode already open before period)
OR Opening_Date BETWEEN @Starting_Date AND @Ending_Date --C Opening date is between report date range (eg: episode was opened at some point during the period)
OR Reverse_Opening_Date BETWEEN @Starting_Date AND @Ending_Date) --D Reverse opening date is between report date range (eg: episode was closed at some point, then reopened during the period)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.