【问题标题】:VSQL: Concatenate two values in same column from same tableVSQL:连接来自同一个表的同一列中的两个值
【发布时间】:2021-01-26 07:39:05
【问题描述】:

我有一个如下所示的表格:

      email           | first_name 
----------------------+------------
 ------@diffem.com    | Matthew
 ------@email.net     | Susan      
 ------@email.net     | Thomas     
 ------@email.com     | Donald     
 ------@email.com     | Paula      

即我有记录,其中每个键(电子邮件)只有一个值(名称),但在其他情况下,每个键有两个值。

我希望输出如下所示:

     email           | first_name  
----------------------+-----------------
------@diffem.com    | Matthew
------@email.net     | Susan and Thomas     
------@email.com     | Donald and Paula  

我尝试了以下方法,但由于按聚合函数分组,它无法正常工作:

CREATE TABLE user.table1 AS 
(
select distinct email
        , case when email_count = 1 then first_name
               when email_count = 2 then (MIN(first_name))||' and '||MAX(first_name))
          else null end as first_name_grouped
FROM (
     SELECT email
          , first_name
          , count(email) over (partition by email) as email_count 
     FROM table
     )
x
)
;

我也尝试过通过电子邮件进行分区,将两个名称放在不同的列中,然后将其连接起来,但最终在我的输出表中出现空白(见下文)

      email           | name1  | name 2
----------------------+--------+-------
 ------@email.net     | Susan  | null   
 ------@email.net     | null   | Donald

有没有办法在 SQL 中做到这一点,而无需创建两个单独的名称列?提前致谢。

【问题讨论】:

    标签: sql vsql


    【解决方案1】:

    您想要完成的工作可以在 MYSQL 中完成,例如

    SELECT email, GROUP_CONCAT(first_name)
    FROM table
    GROUP BY email
    
    

    MS SQL server 中有类似的函数叫 STRING_AGG() ,你可以在这里查看更多https://database.guide/mysql-group_concat-vs-t-sql-string_agg/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      相关资源
      最近更新 更多