操作顺序

pgky5nke  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(272)

试着找出如何正确地排序以得到预期的结果。我想要的是a是真的,b,c,d中的任何一个也是真的。开始日期和结束日期在代码的前面定义。
如果我使用a&&((b)|(c)|(d)),就像下面写的那样,我不会得到返回的结果。
如果我使用a&&(b | | c | | d),我认为在逻辑上与上面的相同,也不会返回任何结果。
如果我使用a&&b | | | c | | d,我认为将a和b分组在一起,我会得到几千个结果
如果在语句之间加上括号,就会出现错误(无效语法)

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)

预期结果:
1858年是数据库说“它没有关闭”的一年。所以在这个例子中,除了第14行之外,所有这些都包括在内,这是在我们定义的结束日期之前关闭的。第5行和第6行也会包括在内,因为这一集在我们评估期间是开放的。

编辑:添加了编码的开始和结束日期以及一些预期结果。

zbdgwd5y

zbdgwd5y1#

只要保持 REPORTING_UNIT = '36B11' AND Closing_Date BETWEEN @Starting_Date AND @Ending_Date 环境条件 WHERE 子句并查看得到的结果,然后添加 OR 条件一个接一个,你可能会知道为什么会发生这种情况。另外,在粗略地浏览了一下上面的数据之后,逻辑上应该只包括第5行。 BETWEEN 子句只检查日期范围,第5行满足该条件。

icnyk63a

icnyk63a2#

下面的代码减去or序列中多余的圆括号,应该可以工作了。
你对“开始日期”和“结束日期”的值有信心吗?

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)

相关问题