我想你可以使用這樣的查詢:
WITH t1 AS (
SELECT *,
LAG(quantity) OVER (PARTITION BY m_id ORDER BY id) as pq, -- Previous quantity based on id
LEAD(quantity) OVER (PARTITION BY m_id ORDER BY id) as nq -- Next quantity based on id
FROM yourTable
), t2 AS (
SELECT id, m_id, 1 as ord,
CASE
-- If sign is changed and quantity is bigger than that use next quantity
WHEN (SIGN(nq) <> SIGN(quantity)) AND (ABS(quantity) > ABS(nq)) THEN -nq
-- If sign is changed and quantity is bigger than that use previous quantity
WHEN (SIGN(pq) <> SIGN(quantity)) AND (ABS(quantity) > ABS(pq)) THEN -pq
-- Else use original quantity
ELSE quantity
END As quantity
FROM t1
UNION ALL -- Add extra rows
SELECT id , m_id,
CASE
-- Set order to be higher than original quantity
WHEN (SIGN(nq) <> SIGN(quantity)) AND (ABS(quantity) > ABS(nq)) THEN 0
-- Set order to be lower than original quantity
WHEN (SIGN(pq) <> SIGN(quantity)) AND (ABS(quantity) > ABS(pq)) THEN 2
END As ord,
-- quantity is difference
CASE
WHEN (SIGN(nq) <> SIGN(quantity)) AND (ABS(quantity) > ABS(nq)) THEN nq + quantity
WHEN (SIGN(pq) <> SIGN(quantity)) AND (ABS(quantity) > ABS(pq)) THEN pq + quantity
END As quantity
FROM t1
WHERE
-- Find differences more
1 = CASE
WHEN (SIGN(nq) <> SIGN(quantity)) AND (ABS(quantity) > ABS(nq)) THEN 1
WHEN (SIGN(pq) <> SIGN(quantity)) AND (ABS(quantity) > ABS(pq)) THEN 1
ELSE 0
END)
SELECT
-- Use new values for id
ROW_NUMBER() OVER (ORDER BY id, ord) As id,
m_id, quantity
FROM t2;
當沒有在您的樣本數據中的任何唯一的列,您可以指定下一行,沒有達到這一結果的任何擔保;)。 –
啊我給出了一個簡短的問題。桌子上有一個主鍵。修改樣本數據 – user1572215
對於'id'的每個值,您總是有1或2行,從不更多? – Patrick