【问题标题】:SQL - spliting one column to two separated (diffrent condition)SQL - 将一列分成两列(不同的条件)
【发布时间】:2022-01-20 07:26:46
【问题描述】:

我不知道如何将一列分成两列以不同的条件分开。

如果联系人类型 == 'E' 想保存 AS 电子邮件,否则输入 == '6' 保存 AS 电话。

我需要这样的结果:

【问题讨论】:

  • 我不明白你的要求,你已经知道了(按类型),那为什么要分成不同的列呢?无论如何,这意味着什么,您是在谈论选择还是更改 KONTAKTI?,请将您的预期结果添加为文本..
  • 请将数据和代码作为文本而不是图像发布。同时提供所需的输出。
  • 这能回答你的问题吗? Mysql select two rows in one

标签: mysql sql select


【解决方案1】:

你想要 CASE 表达式

select *, 
   case when type = 'E' then contact end email,
   case when type = '6' then contact end phone
from KONTAKTI

【讨论】:

    【解决方案2】:

    如果您想将这些列添加到表中,有两种方法可以实现。

    首先创建一个带有所需更改的 kontakti 副本。 请注意,我必须假设您的数据类型。

    create table kontakti_temp (
        ac_subject varchar(8),
        type char(1),
        phone varchar(16),
        email varchar(256)
    );
    

    然后将 kontakti 中的数据插入到 kontakti_temp 中,并使用大小写拆分联系人字段。

    insert into kontakti_temp
    select ac_subject
          , type
          , case when type = '6' then contact end as phone
          , case when type = 'E' then contact end as mail
    from kontakti;
    

    然后相应地重命名两个表

    或者你可以使用创建表作为语句

    create table kontakti_temp as
    select ac_subject
          , type
          , case when type = '6' then contact end as phone
          , case when type = 'E' then contact end as mail
    from kontakti;
    

    kontakti_temp 中列的数据类型将来自上述 select 语句返回的数据类型。

    【讨论】:

      【解决方案3】:

      选择:

      select ac_subject,
         max(case when type = '6' then contact end) phone,
         max(case when type = 'E' then contact end) email
      from kontakti
      group by ac_subject
      ;
      

      测试 DDL:

      create table kontakti (
          ac_subject varchar(8),
          type char(1),
          contact varchar(256)
      );
        
      INSERT INTO kontakti
          (`ac_subject`, `type`, `contact`)
      VALUES
          ('a1', 'E', 'email@gmai.com'),
          ('a1', '6', '41895478'),
          ('b2', 'E', 'aa@emai.si'),
          ('v5', '6', '243243'),
          ('v5', 'E', 'me@email.si')
      ;
      
      create table kontakti_temp as
      select ac_subject,
         max(case when type = 'E' then contact end) email,
         max(case when type = '6' then contact end) phone
      from kontakti
      group by ac_subject
      ;
      

      输出:

      ac_subject phone email
      a1 41895478 email@gmai.com
      b2 (null) aa@emai.si
      v5 243243 me@email.si

      【讨论】:

        猜你喜欢
        • 2020-02-18
        • 1970-01-01
        • 2019-11-22
        • 1970-01-01
        • 2020-09-30
        • 2018-10-05
        • 1970-01-01
        • 2018-06-12
        • 1970-01-01
        相关资源
        最近更新 更多