我有一个像这样的表REPORTS:
DBSCODE RPTDATE DBSSEQ
AAA 2012-01-31 1
AAA 2012-02-29 1
AAA 2012-02-29 2
AAA 2012-03-31 1
BBB 2012-01-31 1
BBB 2012-01-31 2
我想为每个dbscode
返回每个rptdate
的最大序列的详细信息。但是,我现在正在运行的查询仅在最大dbsseq
>时返回给我。 1.
我正在执行:
select a.dbscode, a.rptdate, a.dbseq
from REPORTS as a
inner join
(select rptdate, max(dbsseq) as 'Last'
from REPORTS
group by rptdate) as b
on a.rprtdate = b.last
我的结果是:
DBSCODE, RPTDATE, DBSSEQ
AAA, 2012-02-29, 2
BBB, 2012-01-31, 2
答案 0 :(得分:1)
<强>更新强>
我重新读了你的问题,我相信你要找的是这个简单的查询..
SELECT
dbscode, rptdate, max(dbsseq)
FROM
REPORTS
GROUP BY
dbscode,
rptdate
演示 http://sqlfiddle.com/#!3/b16ba/13
初步回答
在子查询中,您还需要按 DBSCODE
进行分组。
SELECT
a.dbscode, a.rptdate, a.dbsseq
FROM
REPORTS as a
INNER JOIN
(SELECT
dbscode, rptdate, MAX(dbsseq) AS 'Last'
FROM
REPORTS
GROUP BY dbscode, rptdate) as b
ON a.dbsseq = b.last
AND a.dbscode = b.dbscode
AND a.rptdate = b.rptdate
击> <击> 撞击>
答案 1 :(得分:0)
select dbscode,
rptdate,
dbseq
from (
select dbscode, rptdate, dbseq,
row_number() over (partition by dbscode order by rptdate desc) as rn
from reports
) t
where rn = 1;
如果有多个行具有相同的rptdate,则只返回一个。如果您不想这样做,请使用dense_rank()
代替row_number()