我有一张表table1
Item_Name | Type | Qty | Amount
A Like 2 10
B Love 1 20
C Ours 1 10
A Love 1 10
A Like 1 10
B Ours 1 10
我需要一个o / p,如下所示
Item_Name Like | Love | Ours Like | Love | Ours
Amount Qty
A 20 10 0 3 1 0
B 0 20 10 0 1 1
C 0 0 10 0 0 1
我如何实现所需的o / p。我无法实现同样的目标。请帮忙
答案 0 :(得分:3)
一种方法是使用分组和条件聚合来获得所需的输出:
SELECT Item_Name,
SUM(Case WHEN Type='Like' THEN Amount ELSE 0 END) AS Like_Amount,
SUM(Case WHEN Type='Love' THEN Amount ELSE 0 END) AS Love_Amount,
SUM(Case WHEN Type='Ours' THEN Amount ELSE 0 END) AS Ours_Amount,
SUM(Case WHEN Type='Like' THEN Qty ELSE 0 END) AS Like_Qty,
SUM(Case WHEN Type='Love' THEN Qty ELSE 0 END) AS Love_Qty,
SUM(Case WHEN Type='Ours' THEN Qty ELSE 0 END) AS Ours_Qty
FROM table1
GROUP BY Item_Name
ORDER BY Item_Name
如果Type
列中的可能值列表已修复,则上述查询有效。如果这些值可以更改,则需要使用其他方法(例如PIVOT
)