1

let's assume I have a table with employee production

id work_order product qty qty_to_sum
1 200 ABC 25
2 200 ABC 25

i would like to see this result:

id work_order product qty qty_to_sum
1 200 ABC 25 25
2 200 ABC 25 0

I want to place a value of qty in qty_to_sum column based on distinct work_order and product columns combination, so when I get the first distinct result I place a value in qty_to_sum and each row with the same work_order and product will get 0. I tried to use row_number but I didn't get what I needed.

1
  • 2
    I tried to use row_number Show your "attempt". Commented Mar 2, 2022 at 12:31

2 Answers 2

1

You can try to use ROW_NUMBER window function then use CASE WHEN to judgment the first per work_order,product will show the value, others will display 0

Query 1:

SELECT *,
       (CASE WHEN ROW_NUMBER() OVER(PARTITION BY work_order,product  ORDER BY id)  = 1 THEN qty ELSE 0 END) 'qty_to_sum'
FROM T

Results:

| id | work_order | product | qty | qty_to_sum |
|----|------------|---------|-----|------------|
|  1 |        200 |     ABC |  25 |         25 |
|  2 |        200 |     ABC |  25 |          0 |
Sign up to request clarification or add additional context in comments.

Comments

1

Use SUM with a window OVER, like :

SUM(qty) OVER(PARTITION BY work_order, product ORDER BY id DESC)

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.