我有一个查询来获取一些数据:
select max(v.SEQUENCENO) as vmaxseq, v.CODE, v.NAMECODE, v.CODENO from smalltbl v join
(select max(SEQUENCENO) as maxseq, CODE, CODENO from smalltbl group by CODE, CODENO) sm
on sm.CODE = v.CODE and sm.CODE = 'D50451489'
group by v.CODE, v.NAMECODE, v.CODENO;
但是当我跑步时,它会返回比我预期更多的数据:
我想要的只是在每个CODENO上返回VMAXSEQ的最大值,如下所示:
如何编写查询以仅获取这2个数据?
谢谢!
答案 0 :(得分:1)
您可以使用分析功能执行所需操作。我认为你想要的查询是:
select sm.*
from (select sm.*, max(SEQUENCENO) over (partition by codeno) as maxseq
from smalltbl sm
where sm.CODE = 'D50451489'
) sm
where sequenceno = maxseq;
答案 1 :(得分:0)
namecode是你的问题。因为它与你的行不同而且与codeno没有直接关系,所以你基本上都会得到一个笛卡尔积。
答案 2 :(得分:0)
可能是这样的东西
SELECT T.*
FROM smalltbl T INNER JOIN
(
SELECT codeno,Max(SEQUENCENO) As vmaxseq
FROM smalltbl where CODE = 'D50451489'
GROUP BY codeno
) T1 ON T.SEQUENCENO = T1.vmaxseq AND T.codeno = T1.codeno
答案 3 :(得分:0)
试试这个
select
vmaxseq, CODE, NAMECODE, CODENO
FROM (
select
vmaxseq, CODE, NAMECODE, CODENO,
FIRST_VALUE(vmaxseq) OVER (ORDER BY vmaxseq DESC) as firstmax
from (
select
max(v.SEQUENCENO) as vmaxseq,
v.CODE,
v.NAMECODE,
v.CODENO,
from smalltbl v
join (select max(SEQUENCENO) as maxseq, CODE, CODENO from smalltbl group by CODE, CODENO) sm
on sm.CODE = v.CODE and sm.CODE = 'D50451489'
group by v.CODE, v.NAMECODE, v.CODENO
)
) where firstmax = vmaxseq