【问题标题】:How to get multiple rows into single row with different columns如何将多行变成具有不同列的单行
【发布时间】:2015-10-29 06:05:30
【问题描述】:

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

性别 - 计数值

男 - 9

女性 - 4

预期输出:

男 - 女

9 - 4

【问题讨论】:

    标签: mysql


    【解决方案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

    【讨论】:

      【解决方案2】:
      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 行。

      【讨论】:

      • 并且在大多数应用程序中,交叉连接将被常规的自连接所取代(在其他一些字段上进行连接)。
      • 我们需要检查这样的模式。我展示了一个。 OP没有。魔鬼在细节中。所以我正在查看您的标签专长,@user3580870。在这里帮助我
      • 我喜欢有趣的问题。这是一。喜欢避免不必要的数据透视表
      • 在实际应用程序中,OP 可能意味着对每个类别(例如美国的每个州)进行性别计数。在这种情况下,人们会在状态字段“上”自我加入。
      • 我完全支持现实世界的模式@user3580870 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2021-08-05
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多