2015-08-08 104 views
0

我在我的表中的行:分離行成多行基於數量

id m_id quantity 
1 1 1500 
2 1 -1000 
3 2 -3000 
4 2 2000 
5 3 400 
6 3 -1000 
7 4 500 
8 4 -500 
9 5 1500 

我想創建一個視圖,將返回此:

id m_id quantity 
    1 1 500 
    2 1 1000 
    3 1 -1000 
    4 2 -1000 
    5 2 -2000 
    6 2 2000 
    7 3 400 
    8 3 -400 
    9 3 -600 
    10 4 500 
    11 4 -500 
    12 5 1500 

查看將返回相等值正面/負面,並將其餘分隔在不同的行中。因此,如果對於給定的m_id,正數和負數不同,那麼兩行被分成三行。

+0

當沒有在您的樣本數據中的任何唯一的列,您可以指定下一行,沒有達到這一結果的任何擔保;)。 –

+0

啊我給出了一個簡短的問題。桌子上有一個主鍵。修改樣本數據 – user1572215

+0

對於'id'的每個值,您總是有1或2行,從不更多? – Patrick

回答

0

我想你可以使用這樣的查詢:

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; 
+0

那樣工作,就像一個魅力一樣。謝謝 – user1572215

+0

但我必須說,這將需要我花很多時間來了解這是如何工作.... – user1572215

+1

我添加一些說明;)。 –