首页 > 解决方案 > 从不同列上同时包含 MIN 和 MAX 子句的行获取属性

问题描述

我有下表:

在此处输入图像描述

对于每个(id_notification/no_doc),我想要具有最小 no_ligne 的行,然后是 maximim dt_capt。在这种情况下,结果将是第三行。我还需要有一列来指示我们为每个 (id_notification/no_doc) 拥有的行数。在这种情况下,它将是 4。

我所做的是第一次加入有行no_ligne=min(no_ligne)(我知道这可能更容易),然后第二次加入有行dt_capt=max(dt_capt)但如果有 a 的行max(dt_capt)没有 no_ligne 则它不起作用等于min(no_ligne)。这是我尝试过的:

select * from
(select a.id_notification, a.no_doc, b.minlignes, b.nblignes, a.dt_capt
from ${use_database}.lkr_send_editique as a
join
(select id_notification, no_doc, count(no_ligne) as nblignes, min(no_ligne) as minlignes from ${use_database}.lkr_send_editique group by id_notification, no_doc) as b
on a.id_notification=b.id_notification and a.no_doc=b.no_doc and b.minlignes=a.no_ligne) as tt

join

(select s.id_notification, s.no_doc, s.dt_capt,
s.typ_mvt from ${use_database}.lkr_send_editique as s
join
(select id_notification, no_doc, max(dt_capt) as dtmax FROM ${use_database}.lkr_send_editique group by id_notification, no_doc) as c
on s.id_notification=c.id_notification and s.no_doc=c.no_doc and s.dt_capt=c.dtmax and s.dt_capt=c.dtmax) as maxxx

on tt.id_notification=maxxx.id_notification and tt.no_doc=maxxx.no_doc and tt.dt_capt=maxxx.dt_capt;

标签: sqljoinhive

解决方案


对于每个(id_notification/no_doc),我想要具有最小 no_ligne 的行,然后是 maximim dt_capt。在这种情况下,结果将是第三行。

您可以使用row_number()

select t.*
from (select t.*,
             count(*) over (partition by id_notification, no_doc) as cnt
             row_number() over (partition by id_notification, no_doc order by no_ligne, dt_capt desc) as seqnum
      from ${use_database}.lkr_send_editique t
     ) t
where seqnum = 1;

推荐阅读