SQL查询到组列

时间:2018-12-03 10:24:59

标签: sql group-by db2

我正在运行一个查询,我只想显示不同的客户。

目前,我正在接收具有多个记录的记录,例如,项目.render()的3条记录。我只想返回序列中的最后一条记录。

我的代码:

A0003

数据样本:

select OJCUNO AS Item,OJPRRF as code,OJFVDT as From Date, OJLVDT as To Date
from M3FDBPRD.OPRICH 
WHERE
   OJCUNO in ( Select max(OJCUNO) FROM OPRICH group by OJCUNO )

预期结果:

Item        Code    From Date       To Date
A0007       AD      20030301        20161231
A0008       AF      20030301        20161231
A0009       AL      20030301        20121229
A0009       AL      20030301        20121231

2 个答案:

答案 0 :(得分:0)

我在这里只是一个刺,因为我无权访问要测试的DB2数据库,但是:

SELECT *
FROM
(
select OJCUNO AS Item,
OJPRRF as code,
OJFVDT as From Date,
OJLVDT as To Date,
ROW_NUMBER() OVER (PARTITION BY OJCUNO, OJPRRF ORDER BY OJFVDT DESC, OJLVDT DESC) AS RNum
from M3FDBPRD.OPRICH 
WHERE
   OJCUNO in ( Select max(OJCUNO) FROM OPRICH group by OJCUNO )
) a
WHERE a.RNum = 1

答案 1 :(得分:0)

只需使用<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <div class="input-group input-group-sm w-50 m-4"> <input class="form-control" type="text"> <div class="input-group-prepend input-group-append"> <div class="input-group-text">@</div> </div> <input class="form-control"></input> </div>

row_number()

如果您使用正确的列,则使用相关子查询的方法将起作用:

select OJCUNO AS Item, OJPRRF as code ,OJFVDT as FromDate, OJLVDT as ToDate
from (select o.*,
             row_number() over (partition by ojcuno order OJPRRF desc, OJLVDT desc) as seqnum
      from M3FDBPRD.OPRICH o
     ) o
where seqnum = 1;