我有以下表结构
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
背后的动机是在单独的栏目中获得销售和购买数据
答案 0 :(得分: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
答案 1 :(得分: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