【问题标题】:Merge 2 tables without repeat data合并2个没有重复数据的表
【发布时间】:2020-09-17 22:59:53
【问题描述】:

我需要合并下表。

表 1

UserID |TopicName
1      |Topic1
1      |Topic2
2      |Topic1
2      |Topic2
2      |Topic3

表2

UserID |Levelname
1      |level1
1      |level2
1      |level3
1      |level4
2      |level1

输出

UserID |TopicName|LevelName
1      |Topic1   |Level1
1      |Topic2   |Level2
1      |         |Level3
1      |         |Level4


TopicName|LevelName
1      |Topic1   |Level1
1      |Topic2   |Level2
1      |         |Level3
1      |         |Level4

【问题讨论】:

  • 请用您正在运行的数据库标记您的问题:mysq、oracle、sql-server....?
  • 如果这是 mysql,DISTINCT 是返回非重复行的一种选择dev.mysql.com/doc/refman/8.0/en/select.html
  • 请尝试一下,向我们展示您的尝试 - 这不是代码编写服务。

标签: sql sql-server database left-join window-functions


【解决方案1】:

您似乎想根据位置匹配具有相同userid 的行。您可以枚举子查询中的行,然后左连接。

为了使其始终如一地工作,您需要一个列来定义每个表中每一行的位置 - 因为您的数据中没有显示这方面的内容,所以我使用了另一个列表 - 但您可能想要更改它。

select t2.userid, t1.topicname, t2.levelname
from (
    select t2.*, row_number() over(partition by userid order by topicname) rn
    from table2 t2
) t2
left join (
    select t1.*, row_number() over(partition by userid order by levelname) rn
    from table2 t1
) t1 on t1.userid = t2.userid and t1.rn = t2.rn

您可以在查询末尾添加where 子句以过滤给定的userid,如您的预期结果所示:

where t2.userid = 1

如果两个表中都可能存在“缺失”行,那么full join 是更好的选择:

select coalesce(t1.userid, t2.userid) userid, t1.topicname, t2.levelname
from (
    select t2.*, row_number() over(partition by userid order by topicname) rn
    from table2 t2
) t2
full join (
    select t1.*, row_number() over(partition by userid order by levelname) rn
    from table2 t1
) t1 on t1.userid = t2.userid and t1.rn = t2.rn

【讨论】:

  • 谢谢,GMB 第二个查询运行良好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 2021-12-29
  • 2019-01-28
  • 2012-04-17
相关资源
最近更新 更多