First Value函数在Oracle中返回null

时间:2016-10-25 12:35:49

标签: sql oracle

我需要获取第一个结果。

我使用以下查询执行操作

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<div ng-app="myModule">
  <div ng-controller="myController">

  </div>

</div>

让我们假设table2中没有记录。在那种情况下,我的预期输出应该是

select id,firstname,dob,assignment
from (
     select table1.id as id, 
            table1.name as firstname,
            table1.dob as dob,
            First_value(table2.Res)over (partition by table2.id order by table2.date asc) f,
            table2.Res as assignment
     from table1,table2
     where  table1.id  = table2.id and
) where assignment = f

如果table2中有记录,查询工作正常。但是,如果table2中没有特定员工的记录,则上述查询不会返回任何结果。

2 个答案:

答案 0 :(得分:1)

评论太长了。

当然,如果其中一个表为空,则查询不返回任何行。这就是交叉连接和内部连接的工作方式。

大概你想要一个left join和一个更简单的查询:

select t1.id as id, t1.name as firstname,t1.dob as dob,
       First_value(t2.Res)over (partition by t2.id order by t2.date asc) f,
       t2.Res as assignment
from table1 t1 left join
     table2 t2
     on t1.id  = t2.id and t2.Res = 'f';

答案 1 :(得分:1)

试试这个:

SELECT id,firstname,dob,assignment
FROM (
       SELECT table1.id as id, 
              table1.name as firstname,
              table1.dob as dob,
              First_value(table2.Res)over(partition by table2.id order by table2.date asc) f,
              table2.Res as assignment
       FROM table1
       LEFT JOIN table2 ON table1.id  = table2.id 
 ) WHERE ( assignment = f OR ( assignment IS NULL AND f IS NULL) )