I have the next table
Product | Plant | Store | Text | Week | Date | Stock |
---|---|---|---|---|---|---|
123456 | A123 | Z12 | HelloWorld | 1 | 2001-01-01 | 20 |
123456 | A123 | Z12 | HelloWorld | 2 | 2001-01-08 | -15 |
123456 | A123 | Z12 | HelloWorld | 3 | 2001-01-16 | -20 |
789123 | B345 | 123 | HelloWorld1 | 1 | 2001-01-01 | 10 |
789123 | B345 | 123 | HelloWorld1 | 2 | 2001-01-08 | 20 |
789123 | B345 | 123 | HelloWorld1 | 3 | 2001-01-16 | 30 |
So I would like to get the row for the first negative value but if is not negative values then get the last positive value. Also restructured the table like this.
Product | Plant | Store | Text | Date_Start | Stock_Start | Date_Finished | Stock_Finished |
---|---|---|---|---|---|---|---|
123456 | A123 | Z12 | HelloWorld | 2001-01-01 | 20 | 2001-01-08 | -15 |
789123 | B345 | 123 | HelloWorld1 | 2001-01-01 | 10 | 2001-01-16 | 30 |
I try multiple query’s but the one with the nearest result is as follows:
SELECT Product,Plant,Store,Text,Date, Stock FROM table
WHERE (Stock)<0
order by Product,Plant,Store,Text,Date, Stock asc
Also I tried to use FETCH FIRST 1 ROWS ONLY
but I got the next error ERROR: Syntax error at or near "FIRST"
.
The other query is as follows:
WITH added_row_number AS (
SELECT
*,
ROW_NUMBER() OVER(PARTITION BY Product,Plant,Store ORDER BY Date ASC) AS row_number
FROM MM_STOCK
)
SELECT
*
FROM added_row_number
WHERE (Stock)<0 AND row_number = 1;
But beware the data and if I add a case stament I got the error ERROR: Syntax error at or near "CASE"
. Any help?
2
Answers
Some Subselects can be used, to solve this
fiddle
you don’t need for this aggregation, i can’t find a Version postgres that doesn’t work
fiddle
You could rephrase this as "latest positive stock per product, also latest negative per product", which implies
As mentioned in the comment, usually the 1 per product translates into a
distinct on
: demo