Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql DB2查询-消除最大值_Sql_Db2 - Fatal编程技术网

Sql DB2查询-消除最大值

Sql DB2查询-消除最大值,sql,db2,Sql,Db2,我简化了以下问题: 我有一张包含动物的桌子,例如: ID Type Birthday 1 Dog 1.1.2011 2 Cat 2.1.2009 3 Horse 5.1.2009 4 Cat 10.6.1999 5 Horse 9.3.2006 我知道所有的动物都属于一个家庭。现在,我想看到每个家庭的所有后代,但我不想看到家族创始人的名字 对于上面

我简化了以下问题:

我有一张包含动物的桌子,例如:

ID       Type      Birthday
1        Dog       1.1.2011  
2        Cat       2.1.2009
3        Horse     5.1.2009
4        Cat       10.6.1999
5        Horse     9.3.2006
我知道所有的动物都属于一个家庭。现在,我想看到每个家庭的所有后代,但我不想看到家族创始人的名字

对于上面的简单示例,我只想看到:

ID       Type      Birthday
2        Cat       2.1.2009
3        Horse     5.1.2009
到目前为止,我还没有找到一种方法将条目分组,然后从每个组中删除第一个条目。我只能找到如何删除特定的行

甚至有可能解决这个问题吗


非常感谢你的帮助。非常感谢。

一个简单但不必要的高效方法可以是:

select
  id, type, birthday
from animals
  left join
  (select type, min(birthday) min_birthday
  from animals
  group by type) a 
     on a.type=animals.type and a.min_birthday = animals.birthday
where a.type is null;
为了获得最佳效率,您可以使用分析功能:

select id, type, birthday
from(
    select
      id, 
      type, 
      birthday, 
      row_number() over (partition by type order by birthday) as rnk
    from animals
) a
where rnk >=2

有关分析函数的更多示例,您可以在SQL Server中阅读以下内容:

select
  id, type, birthday
from (
    select
      id, type, birthday,
      row_number() over (partition by type order by birthday asc) r
    from
      animals
) q
where r > 1
row_number函数也可以在DB2中使用,但我不知道在什么情况下/版本


已编辑,下面是注释。

从我的回答中可以看出,它们在2004年就存在了。请参阅文章如果ID是表的主键,我相信您的第一次查询将不会返回任何内容。但是您的第二个应该可以很好地工作。您是对的,谢谢,我已经使用了另一个纯SQL解决方案。在第二个解决方案中,DB/2是否需要派生表上的别名?@muistooshort我不知道,而且我手头没有DB2。不过,我觉得还是把它说出来比较好。只需两秒钟…非常感谢您的帮助!我们现在使用的是上述文章中提到的第二种解决方案。@mu太短了:更像是每个分区的偏移量1,我认为这与简单的偏移量1不同。我的意思是,偏移量不支持分区,是吗?@AndriyM:我认为你对这个问题的解释是正确的。看起来又是一份工作了。这将返回应该忽略的内容。也就是说,如果条件相反,这将是一个正确的答案。OP似乎在寻找,用他们自己的话说,“一种将条目分组,然后从每组中删除第一个条目的方法”。我把第一个条目理解为最早的条目,因此不应返回最早的条目,这反过来意味着只应返回存在较早记录的记录。@AndriyM:你是对的,当然-答案相应地更正。是的,Andriy你是对的:我想删除最早的条目。
select id, type, birthday
from animals a
where exists (select null from animals e
              where e.type = a.type and e.birthday < a.birthday)