0

次のテーブル構造があります

id  item_code      type            qty

1   1011           Purchase        20
2   1011           Purchase        30
3   1011           Sales           -2
4   1011           Purchase        10
5   1011           Sales           -7
6   1011           Sales           -10
7   1011           Purchase        13
8   1011           Purchase        7

次のパターンでデータを取得できるようにテーブルを結合する方法

qty_p   qty_s

20      -2
30      -7
10      -10
13      null
7       null

背後にある動機は、別の列で販売と購入の数値を取得することです

4

2 に答える 2

1

レコードを結合できるように、ここで変数を使用する必要があると思います。

SELECT  a.qty PurchaseQuantity, 
        b.qty SalesQuantity
FROM
        (
            SELECT  @rank1 := @rank1 + 1 Rank1,
                    a.qty
            FROM    tableName a, (SELECT @rank1 := 0) b
            WHERE   a.type = 'Purchase'
            ORDER   BY a.ID
        ) a
        LEFT JOIN
        (
            SELECT  @rank2 := @rank2 + 1 Rank2,
                    a.qty
            FROM    tableName a, (SELECT @rank2 := 0) b
            WHERE   a.type = 'Sales'
            ORDER   BY a.ID
        ) b ON a.Rank1 = b.Rank2
ORDER   BY a.Rank1
于 2013-11-05T10:57:23.757 に答える
1

これを試して:

DECLARE @TABLE TABLE 
(
ID  INT , ITEM_CODE INT,      TYPE   VARCHAR(40)   ,      QTY  INT 
)
INSERT INTO @TABLE
VALUES 
(
1 ,  1011,           'PURCHASE',        20),
(2  , 1011,           'PURCHASE' ,       30),
(3   ,1011,           'SALES'     ,      -2),
(4   ,1011,           'PURCHASE'   ,     10),
(5   ,1011,           'SALES'       ,    -7),
(6   ,1011,           'SALES'        ,   -10),
(7   ,1011,           'PURCHASE'      , 13),
(8   ,1011,           'PURCHASE'       , 7)



SELECT 
T1.QTY_P, T2.QTY_S
FROM (
SELECT ID, 
CASE TYPE WHEN 'PURCHASE' THEN QTY ELSE NULL END AS QTY_P,
CASE TYPE WHEN 'SALES' THEN QTY ELSE NULL END AS QTY_S
, RNO = ROW_NUMBER() OVER (PARTITION BY TYPE ORDER BY ID) 

FROM @TABLE
) T1
LEFT OUTER JOIN 
(
SELECT ID,
CASE TYPE WHEN 'PURCHASE' THEN QTY ELSE NULL END AS QTY_P,
CASE TYPE WHEN 'SALES' THEN QTY ELSE NULL END AS QTY_S,
 RNO = ROW_NUMBER() OVER (PARTITION BY TYPE ORDER BY ID) 

FROM @TABLE 

)T2 ON T1.RNO = T2.RNO AND T1.ID <> T2.ID
WHERE T1.QTY_P IS NOT NULL 
于 2013-11-05T11:58:14.267 に答える