在SQL中,将列转换为行的方式可以使用以下几种方法:
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;
这些都是将列转换为行的常见方法,具体使用哪种方法取决于数据库的支持和查询的需求。