简体   繁体   English

将行转换为列(MySQL)

[英]Transposing rows into columns (MySQL)

So, lets say I have a table called "imports" that looks like this: 因此,可以说我有一个名为“ imports”的表,如下所示:

| id | importer_id | total_m | total_f |
|====|=============|=========|=========|
| 1  |  1          | 100     | 200     |
| 1  |  1          | 0       | 200     |

And I need the query to return it pivoted or transposed (rows to columns) in this way: 我需要查询以这种方式将其旋转或转置(行到列):

| total_m  | sum(total_m) |
| total_f  | sum(total_f) |

I can't think on a way to do this without using another table (maybe a temporary table?) and using unions, but there should be a better way to this anyway (maybe with CASE or IF?). 我无法想到一种无需使用其他表(可能是临时表?)并使用联合的方法,但是无论如何,应该有一个更好的方法(也许使用CASE或IF?)。

Thanks in advance. 提前致谢。

select 'total_m', sum(total_m) from imports
union
select 'total_f', sum(total_f) from imports

http://sqlfiddle.com/#!9/fc1c0/2/0 http://sqlfiddle.com/#!9/fc1c0/2/0

You can "unpivot" by first expanding the number of rows, which is done below by cross joining a 2 row subquery. 您可以通过首先扩展行数来“取消透视”,这可以通过交叉联接2行子查询来完成。 Then on each of those rows use relevant case expression conditions to align the former columns to the new rows ("conditional aggregates"). 然后,在这些行的每一行上,使用相关的case表达式条件将先前的列与新的行对齐(“条件聚合”)。

SQL Fiddle SQL小提琴

MySQL 5.6 Schema Setup : 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)
;

Query 1 : 查询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

Results : 结果

| importer_id | total_type | total |
|-------------|------------|-------|
|           1 |    total_f |   400 |
|           1 |    total_m |   100 |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM