【问题标题】:How to join tables in SQL Server such that join each row once [closed]如何连接 SQL Server 中的表,以便将每一行连接一次 [关闭]
【发布时间】:2020-10-03 18:55:01
【问题描述】:

我有两张表,如下所示:

我需要以某种方式加入他们以实现这个结果集:

你知道我该怎么做吗?

【问题讨论】:

  • 你需要解释你的“逻辑”/意图是什么——仅仅发布这些表格并不能真正告诉我们你想要做什么......
  • 首先命名您的表并解释不同字段的含义以及wiich字段之间的关系。例如:具有相同日期的行是否“属于彼此”?您是否希望具有相同数量的行匹配?这么多问题......解释一下你的推理是什么,从两个表到组合表。
  • use text, not images/links, for text--including tables & ERDs。仅将图像用于无法表达为文本或增强文本的内容。请不要让我们做你的功课。

标签: sql sql-server join select window-functions


【解决方案1】:

您可以使用row_number()full join 枚举每个日期的每个表的行结果:

select 
    t1.prof, 
    t2.project, 
    coalesce(t1.date, t2.date) date,
    t1.amount amount1,
    t2.amount amount2
from (
    select 
        t1.*,
        row_number() over(partition by date order by prof) rn
    from table1 t1
) t1
full join (
    select 
        t2.*,
        row_number() over(partition by date order by project) rn
    from table2 t2
) t2 on t1.date = t2.date and t1.rn = t2.rn

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    相关资源
    最近更新 更多