我目前正在尝试为我们的日志记录创建一个小报告,但它并没有像我预期的那样工作。
我创建了一个查询,当我只有1个LIKE子句时工作正常,但是当我向查询添加OR时,我的结果搞砸了。我不确定为什么会这样。我错过了分组还是什么?
以下是查询的工作原理:
select
s.SupportCode
, s.DateTaken
, s.TakenBy
, s.AllocatedTo
--, p.IndustrySector
from
Support s
join Project p on p.ProjectCode = s.ProjectCode
where
s.DateTaken >= dateadd(month, datediff(month, 0, dateadd(m, -6, current_timestamp)),0)
and s.SupportAction like '%RMC%'
这是结果,这就是我想要的:
╔══════════╦═════════════════════════╦═════╦═════╗
║ 00074062 ║ 2017-01-25 00:00:00.000 ║ JCH ║ JCH ║
║ 00073482 ║ 2016-12-14 00:00:00.000 ║ ROA ║ FJ ║
║ 00072764 ║ 2016-11-10 00:00:00.000 ║ ROA ║ ROA ║
║ 00072660 ║ 2016-11-03 00:00:00.000 ║ FJ ║ FJ ║
║ 00073818 ║ 2017-01-11 00:00:00.000 ║ ROA ║ FJ ║
║ 00070844 ║ 2016-09-14 00:00:00.000 ║ ROA ║ FJ ║
║ 00070988 ║ 2016-09-22 00:00:00.000 ║ ROA ║ ROA ║
╚══════════╩═════════════════════════╩═════╩═════╝
这是我添加其他LIKE子句时的查询:
select
s.SupportCode
, s.DateTaken
, s.TakenBy
, s.AllocatedTo
--, p.IndustrySector
from
Support s
join Project p on p.ProjectCode = s.ProjectCode
where
s.DateTaken >= dateadd(month, datediff(month, 0, dateadd(m, -6, current_timestamp)),0)
and s.SupportAction like '%RMC%'
or s.SupportAction like '%FJ%'
or s.SupportAction like '%DG%'
or s.SupportAction like '%VIC%';
结果如下:
╔══════════╦═════════════════════════╦═════╦══════╗
║ 00031254 ║ 1996-11-04 00:00:00.000 ║ KGB ║ KGB ║
║ 00031279 ║ 1996-11-12 00:00:00.000 ║ TB ║ TMB ║
║ 00031296 ║ 1996-11-18 00:00:00.000 ║ SPB ║ BJR ║
║ 00031402 ║ 1997-01-07 00:00:00.000 ║ AJS ║ AJS ║
║ 00031474 ║ 1997-02-04 00:00:00.000 ║ BJR ║ NULL ║
║ 00031513 ║ 1997-02-19 00:00:00.000 ║ NS ║ NULL ║
║ 00031538 ║ 1997-02-25 00:00:00.000 ║ SPB ║ SPB ║
╚══════════╩═════════════════════════╩═════╩══════╝
为什么会这样?我无法思考为什么。
任何帮助都将不胜感激。
答案 0 :(得分:3)
添加括号怎么样?没有它们您的查询无效。这应该工作:
select
s.SupportCode
, s.DateTaken
, s.TakenBy
, s.AllocatedTo
--, p.IndustrySector
from
Support s
join Project p on p.ProjectCode = s.ProjectCode
where
s.DateTaken >= dateadd(month, datediff(month, 0, dateadd(m, -6, current_timestamp)),0)
and ( s.SupportAction like '%RMC%'
or s.SupportAction like '%FJ%'
or s.SupportAction like '%DG%'
or s.SupportAction like '%VIC%');
答案 1 :(得分:1)
在所有or子句周围加上括号,这就是问题所在。像这样:
and (s.SupportAction like '%RMC%'
or s.SupportAction like '%FJ%'
or s.SupportAction like '%DG%'
or s.SupportAction like '%VIC%');
答案 2 :(得分:0)
When use multiple 'OR' condition in Where clause must use open and close brackets like this
where
(s.DateTaken >= dateadd(month, datediff(month, 0, dateadd(m, -6, current_timestamp)),0))
and (s.SupportAction like '%RMC%'
or s.SupportAction like '%FJ%'
or s.SupportAction like '%DG%'
or s.SupportAction like '%VIC%')