0

I have a following table structure

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

how do i join the table such that i can get data in following pattern

qty_p   qty_s

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

motive behind is this to get sale and purchase figures in separate column

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 回答