[英]Transposing rows into columns (MySQL)
因此,可以说我有一个名为“ imports”的表,如下所示:
| id | importer_id | total_m | total_f |
|====|=============|=========|=========|
| 1 | 1 | 100 | 200 |
| 1 | 1 | 0 | 200 |
我需要查询以这种方式将其旋转或转置(行到列):
| total_m | sum(total_m) |
| total_f | sum(total_f) |
我无法想到一种无需使用其他表(可能是临时表?)并使用联合的方法,但是无论如何,应该有一个更好的方法(也许使用CASE或IF?)。
提前致谢。
select 'total_m', sum(total_m) from imports
union
select 'total_f', sum(total_f) from imports
您可以通过首先扩展行数来“取消透视”,这可以通过交叉联接2行子查询来完成。 然后,在这些行的每一行上,使用相关的case表达式条件将先前的列与新的行对齐(“条件聚合”)。
MySQL 5.6模式设置 :
CREATE TABLE imports
(`id` int, `importer_id` int, `total_m` int, `total_f` int)
;
INSERT INTO imports
(`id`, `importer_id`, `total_m`, `total_f`)
VALUES
(1, 1, 100, 200),
(1, 1, 0, 200)
;
查询1 :
select
*
from (
select
i.importer_id
, concat('total_',cj.unpiv) total_type
, sum(case when cj.unpiv = 'm' then total_m
when cj.unpiv = 'f' then total_f else 0 end) as total
from imports i
cross join (select 'm' as unpiv union all select 'f') cj
group by
i.importer_id
, cj.unpiv
) d
结果 :
| importer_id | total_type | total |
|-------------|------------|-------|
| 1 | total_f | 400 |
| 1 | total_m | 100 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.