【问题标题】:Get attributs from lines whith both MIN and MAX clauses on different columns从不同列上同时包含 MIN 和 MAX 子句的行获取属性
【发布时间】:2019-10-28 11:36:24
【问题描述】:

我有下表:

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

我所做的是第一次加入具有no_ligne=min(no_ligne) 的行(我知道这可能更容易) 然后第二次加入具有dt_capt=max(dt_capt) 的行,但如果具有max(dt_capt) 的行没有等于min(no_ligne) 的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;

【问题讨论】:

    标签: sql join hive


    【解决方案1】:

    对于每个 (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;
    

    【讨论】:

    • @forpas,就是这样。而且我无法编辑评论。也许掩盖它是问题?我可以粘贴地址并到达那里,但单击会引发 404。我会在这里再试一次,不显示文本。关于 Hive 中的窗口函数:cwiki.apache.org/confluence/display/Hive/…
    • 这似乎行得通。我将删除最初的评论以处理不良链接。
    • @Gordon Linoff 我可以将桌子加入另一个桌子吗?请问我该怎么做?我还希望每个 id_notification 的所有行的最小 dt_capt,no_doc。
    • @AbderrahmenM 。 . .您可以使用子查询或 CTE,或者只是将 JOIN 添加到 t
    【解决方案2】:

    使用NOT EXISTS 仅获取 3d 行并加入返回行数的查询:

    select t.*, tt.counter 
    from tablename t inner join (
      select id_notification, no_doc, count(*) counter
      from tablename
      group by id_notification, no_doc 
    ) tt on tt.id_notification = t.id_notification and tt.no_doc = t.no_doc
    where not exists (
      select 1 from tablename
      where id_notification = t.id_notification and no_doc = t.no_doc
      and (no_ligne < t.no_ligne or (no_ligne = t.no_ligne and dt_capt > t.dt_capt))
    )
    

    【讨论】:

      猜你喜欢
      • 2019-01-26
      • 2021-04-03
      • 2012-08-26
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      相关资源
      最近更新 更多