0

I have a query to get some data:

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;

But when I run, it will return more data than I expected:

SQL1

What I want is only return max of VMAXSEQ on each CODENO, something like this:

SQL2

How do I write query to get those 2 data only?

Thank You!

4 Answers 4

1

You can do what you want with analytic functions. I think the query you want is:

select sm.*
from (select sm.*, max(SEQUENCENO) over (partition by codeno) as maxseq
      from smalltbl sm
      where sm.CODE = 'D50451489'
     ) sm
where sequenceno = maxseq;
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Gordon, thanks for your comment, but sometimes the SEQUENCENO is not same.. between CODENO, the SEQUENCENO can be bigger or smaller.. Is that your query still valid?
This query returns the rows with the row(s) with the maximum SEQUENCENO for each CODENO. I would expect difference values of SEQUENCENO on a given CODENO.
Hi Gordon, yeah.. your query is valid! it will always return max SEQUENCENO for each CODENO.. Thanks!
0

namecode is your problem. Because it varies over your rows and doesn't relate directly to codeno, you're essentially getting a cartesian product.

Comments

0

May be Something Like this

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

Comments

0

Try this one

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.