MySQL中的转置(Transpose)是指将表中的行转换为列,或者将列转换为行。在MySQL中,通常使用CASE
语句或PIVOT
操作来实现部分列的转置。
CASE
语句或临时表来实现。假设我们有一个表sales
,结构如下:
CREATE TABLE sales (
id INT AUTO_INCREMENT PRIMARY KEY,
product VARCHAR(50),
region VARCHAR(50),
amount INT
);
插入一些示例数据:
INSERT INTO sales (product, region, amount) VALUES
('ProductA', 'North', 100),
('ProductA', 'South', 150),
('ProductB', 'North', 200),
('ProductB', 'South', 250);
CASE
语句进行静态转置SELECT region,
SUM(CASE WHEN product = 'ProductA' THEN amount ELSE 0 END) AS ProductA,
SUM(CASE WHEN product = 'ProductB' THEN amount ELSE 0 END) AS ProductB
FROM sales
GROUP BY region;
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT CONCAT('SUM(IF(product = ''', product, ''', amount, 0)) AS ', product))
INTO @sql
FROM sales;
SET @sql = CONCAT('SELECT region, ', @sql, ' FROM sales GROUP BY region');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
希望这些信息对你有所帮助!如果有更多问题,欢迎继续提问。
领取专属 10元无门槛券
手把手带您无忧上云