在SQL中,將列轉(zhuǎn)換為行的方式可以使用以下幾種方法:
SELECT customer_id, product, quantity
FROM sales
UNPIVOT
(
quantity
FOR product IN (product_A, product_B, product_C)
) AS unpvt;
SELECT s.customer_id, v.product, v.quantity
FROM sales s
CROSS APPLY
(
VALUES
('product_A', s.product_A),
('product_B', s.product_B),
('product_C', s.product_C)
) AS v (product, quantity);
SELECT customer_id, 'product_A' AS product, product_A AS quantity
FROM sales
UNION ALL
SELECT customer_id, 'product_B' AS product, product_B AS quantity
FROM sales
UNION ALL
SELECT customer_id, 'product_C' AS product, product_C AS quantity
FROM sales;
這些都是將列轉(zhuǎn)換為行的常見方法,具體使用哪種方法取決于數(shù)據(jù)庫的支持和查詢的需求。