TOP 1 for each employee

  • I need to select last order for each employees for homework

    I use northwind database for testing

    I can solve it by correlated subquery but the professor said me it is not optimized.

    Can someone to solve it in efficient way?

    my solution

    select orderid, customerid, employeeid, orderdate

    from orders as o1

    where orderdate = (select max(orderdate) from orders as o2 where o1.employeeid = o2.employeeid);

  • You have a common solution that is used more often than you would expect.

    However, I have a question for you. Do you want a complete solution or just what you need to get to it?

    You could use CTE (Common table expressions) and ROW_NUMBER(). If you need more help you can ask for it.

    If you're just using those columns and the orderid is incremental and you can't change the orders' date then a simple MAX() on orderdate and orderid will work along with a group by.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • You could use CTE (Common table expressions) and ROW_NUMBER().

    I could use Derived Table instead CTE.

  • Yes you can. I just have personal preference for CTEs. 😉

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply