[英]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.