1

I am trying to get the last status a customer had. By browsing examples, I have put together this query, which works:

SELECT table.Card, 
    table.Type, 
    table.Date, 
    ROW_NUMBER() OVER   
        (PARTITION by table.CARD ORDER BY table.date DESC, table.TYPE, table.DATE) rn 
 FROM table 
 WHERE table.Type = 'active' or table.Type = 'erased'

From there, I just need those records where rn=1, but as soon as I try to use itas a subquery as shown below, I get a syntaxis error:

SELECT * FROM (
    SELECT table.Card, 
        table.Type, 
        table.Date, 
        ROW_NUMBER() OVER   
            (PARTITION by table.CARD ORDER BY table.date DESC, table.TYPE, table.DATE) rn 
     FROM table 
     WHERE table.Type = 'active' or table.Type = 'erased'
) WHERE rn=1

It must something simple I am just missing, but I am totally confused. Any help will be appreciated.

1
  • 2
    Your subquery needs an alias. ) AS x WHERE rn = 1; Commented Oct 2, 2014 at 19:10

1 Answer 1

2

You should assign an alias to the INNER select. Try this.

SELECT * FROM (
    SELECT table.Card, 
        table.Type, 
        table.Date, 
        ROW_NUMBER() OVER   
            (PARTITION by table.CARD ORDER BY table.date DESC, table.TYPE, table.DATE) rn 
     FROM table 
     WHERE table.Type = 'active' or table.Type = 'erased'
) foo WHERE rn=1
Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad. Please accept the answer if it works for you. Remember, if you use alias on your sub-query then you can JOIN it with some other tables using that alias :)

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.