Oracle SQL - 查询结果不一致

时间:2016-02-08 14:45:09

标签: sql oracle

我正在尝试编写一个Oracle SQL查询,该查询根据employeeID(每个employeeID的不同范围)选择某个日期范围,然后对该日期范围内每个员工的特定性能指标编号求和。我似乎得到了相同employeeID的不一致结果,具体取决于我如何选择它。这是我的疑问:

select c.employeeID, b.assessmentDate, c.startDate, c.endDate,
sum(case when employeeProductivityMetric='15' then 1 else 0 end) as Metric1,
sum(case when employeeProductivityMetric='20' then 1 else 0 end) as Metric2
from assessmentTable b 
inner join performanceMetricTable c on b.badgeID = c.badgeID
where b.assessmentDate between c.startDate and c.endDate
group by c.employeeID, b.assessmentDate, c.startDate, c.endDate
order by c.employeeID, b.assessmentDate;

请注意,给定的employeeID可以与多个badgeID关联。

当我通过在where子句中添加以下内容来选择一个特定的employeeID(例如,2)时:

where c.employeeID=2

我得到了Metric1和Metric2的一些特定数字:

employeeID  assessmentDate  startDate   endDate    Metric1  Metric2
2           02-Jul-15       01-Jul-15   31-Jul-15  4        5

然而,当我做

where c.employeeID between 1 and 3

我为员工2获得了不同的数字,例如:

employeeID  assessmentDate   startDate  endDate    Metric1  Metric2
2           02-Jul-15        01-Jul-15  31-Jul-15  3        0

有谁知道为什么会这样?我的查询设计有问题吗?

感谢您的任何指示!

纳塔利娅

1 个答案:

答案 0 :(得分:0)

您可以通过检索详细记录来调试此类情况:

尝试比较以下查询

-- matched records for employeeID=2
select c.employeeID, c.badgeID, b.assessmentDate, c.startDate, c.endDate,
employeeProductivityMetric
from assessmentTable b 
inner join performanceMetricTable c on b.badgeID = c.badgeID
where b.assessmentDate between c.startDate and c.endDate
      and c.employeeID=2
order by c.employeeID, c.badgeID, b.assessmentDate;

-- matched records for employeeID between 1 and 3
select c.employeeID, c.badgeID, b.assessmentDate, c.startDate, c.endDate,
employeeProductivityMetric
from assessmentTable b 
inner join performanceMetricTable c on b.badgeID = c.badgeID
where b.assessmentDate between c.startDate and c.endDate
      and c.employeeID between 1 and 3
order by c.employeeID, c.badgeID, b.assessmentDate

最有可能的是,您会发现每个查询返回的badgeIds存在差异。