1

I have a where i store orderrows (salesrow_id), so one line of an invoice, which is part of a order order_id and the price paid for that item

salesrow_id(pk) | order_id | price | name
10                1           5      spaghetti
11                1           4      pizza
12                2           6      salami
13                1           1      vegetables

What i am trying to achieve is to have get the rownumber on the invoice, by order_id and salesrow_id. For example: salesrow_id=13, order_id=1 should return 3, since it's the third item on my invoice for order 1, if sorted by salesrow_id.

I've tried querying using row_number but that works only if i return multiple rows, and i would just like to have the number 3 as a single result.

Could someone push me in the right direction?

1 Answer 1

1

You are looking for row_number(), I think:

select t.*,
       row_number() over (partition by order_id order by sales_row_id) as rownumber
from t;

If you want this for a single row, then use a subquery and filter:

select t.*
from (select t.*,
             row_number() over (partition by order_id order by sales_row_id) as rownumber
      from t
     ) t
where sales_row_id = 13;

If you care about performance, a correlated subquery might be better:

select t.*,
       (select count(*)
        from t t2
        where t2.order_id = t.order_id and t2.sales_row_id <= t.sales_row_id
       ) as rownum
from t
where t.sales_row_id = 13;

Note that row_number() (in the first query) is best for assigning results to the entire table. The correlated subquery would only have better performance when you are selecting one row or a smallish number of rows.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, the keyword here is partition by. I have indeed looked at the row_number() extensively, but i couldn't find a way to do it per "group", which is exactly what the partition by does. You saved the day!

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.