sql - 从不同列上同时包含 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;
解决方案
对于每个(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;
推荐阅读
- android - Android ImageButton 中的圆角不起作用
- python - 使用熊猫将多数据类型数据帧转换为python中的整数编码数据帧
- javascript - 如何测试现有的 Angularjs 整体性能(DOM 渲染)?
- java - 如何使用 Nashorn 引擎调用 Java 对象
- javascript - 操作 Array.map 中的前一项?
- c++ - QString替换引号外的字符
- c# - 将类从 C++ 转换为 C#
- ios - 注释的重用标识符有什么意义
- c# - 如何将 .NET 类库作为 Web 服务运行
- python - Pykafka - 异步发送消息和接收确认