特定数据查询

时间:2018-03-31 03:02:04

标签: sql oracle oracle11g operators

以前主题的链接 - LINKED Oracle - runtime and show data based on inserted year ( not duplicate )

摘要

  

根据上面的链接,我继续编写更具体的结果   我想要的,我在代码中遇到了一些问题   使用“WHERE”语句显示使用后的特定数据   替代变量(&)

根据Mr.Barboros提供的工作代码,我想添加一些查询,仅显示一些位置,例如,

我有查询2016,它应该只显示2个结果

FACILITYNAME COUNT_TIMES    MONTHS
Science Lab     1             4
Science Lab     1             5
  

但它总是显示额外的位置,即使在2016年也是生物学   是没有生物学插入数据库。    - 如果我用“或”添加更多位置,它仍会继续显示结果,下面是我查询的代码。

SELECT f.FACILITYNAME,COUNT(*) AS count_times, EXTRACT (MONTH FROM b.Timebooked ) AS MONTHS
FROM BookingTable b
JOIN FacilityTable f ON b.FACILITYNO = f.FACILITYNO
WHERE TO_CHAR(b.Timebooked , 'YYYY') = 2018
AND f.FACILITYNAME = 'Toilet' OR f.FACILITYNAME = 'Science Lab' OR  f.FACILITYNAME = 'Biology Lab'
GROUP BY (EXTRACT (MONTH FROM b.Timebooked )),f.FACILITYNAME
ORDER BY (EXTRACT (MONTH FROM b.Timebooked ));

http://sqlfiddle.com/#!4/13a6a/9

  

我想要的结果是,当我进入任何一年时,只显示   厕所,科学实验室生物学实验室

1 个答案:

答案 0 :(得分:0)

需要添加'()'在' OR'周围条件。如果没有括号,AND将优先于OR。请参阅SQL Logic Operator Precedence

试试这个:

SELECT f.FACILITYNAME,COUNT(*) AS count_times, EXTRACT (MONTH FROM b.Timebooked ) AS MONTHS
FROM BookingTable b
JOIN FacilityTable f ON b.FACILITYNO = f.FACILITYNO
WHERE TO_CHAR(b.Timebooked , 'YYYY') = 2018
AND (f.FACILITYNAME = 'Toilet' OR f.FACILITYNAME = 'Science Lab' OR  f.FACILITYNAME = 'Biology Lab')
GROUP BY (EXTRACT (MONTH FROM b.Timebooked )),f.FACILITYNAME
ORDER BY (EXTRACT (MONTH FROM b.Timebooked ));

如果没有括号,您的查询实际上是这样做的(这是不正确的):

SELECT f.FACILITYNAME,COUNT(*) AS count_times, EXTRACT (MONTH FROM b.Timebooked ) AS MONTHS
FROM BookingTable b
JOIN FacilityTable f ON b.FACILITYNO = f.FACILITYNO
WHERE ( TO_CHAR(b.Timebooked , 'YYYY') = 2018
AND  f.FACILITYNAME = 'Toilet') OR f.FACILITYNAME = 'Science Lab' OR  f.FACILITYNAME = 'Biology Lab' 
GROUP BY (EXTRACT (MONTH FROM b.Timebooked )),f.FACILITYNAME
ORDER BY (EXTRACT (MONTH FROM b.Timebooked ));