如何将多行放入具有不同列的单行中

时间:2015-10-29 06:05:31

标签: mysql

我有以下表结构,下面列出了预期输出如何实现结果:

性别 - 计数值

男 - 9

女性 - 4

预期输出:

男 - 女

9 - 4

2 个答案:

答案 0 :(得分:1)

您可以尝试这样:

SELECT  
        max(case when `gender` = 'Male' then countvalue end) as Male,
        max(case when `gender` = 'Female' then countvalue end) as Female
FROM    test 

<强> SQL FIDDLE DEMO

答案 1 :(得分:1)

create table k
(   gender varchar(20) not null,
    theCount int not null
);
insert k(gender,theCount) values ('male',9),('female',4);


select a.theCount as male, b.theCount as female 
from k a 
cross join k b 
where a.gender='male' and b.gender='female';

+------+--------+
| male | female |
+------+--------+
|    9 |      4 |
+------+--------+

交叉连接是笛卡尔积。但是1行1行是结果集中的1行。