【问题标题】:Replacing a value in a table and then joining it to another table替换表中的值,然后将其连接到另一个表
【发布时间】:2017-03-08 15:58:15
【问题描述】:

网站是全新的,这是我的第一个问题!抱歉,我的 SQL 技能非常有限。我主要使用 Tableau,但需要在 Tableau 中创建自定义 SQL 连接。

我有 2 个表(C 表和 P 表)需要通过“订单”字段(在两个表中都可以找到)和“前缀”字段(仅在 C 表中找到但希望更改P 表中的“合同”字段进行连接)。只有两个值需要更改。如果contract="1234",则改为"ABC。如果contract="5678",则改为"XYZ"。

一旦更改了这些值,P 表中的合同可以连接到 C 表中的前缀。

抱歉,我无法更好地解释这一点,但就像我说的,我在 SQL 方面的经验非常有限。任何帮助将不胜感激!

【问题讨论】:

    标签: sql join case tableau-api


    【解决方案1】:

    您可以使用子查询来做到这一点。

    select * 
        from C
        inner join (
            select *,
                    case contract when 1234 then ABC
                                  when 5678 then XYZ
                                  else contract
                    end as changed_contract -- or whatever name you like
                from P
        ) P on P.changed_contract = C.prefix
            and P.orders = C.orders
    

    子查询中的表将为您提供 P 中的所有字段,包括一个新字段,该字段考虑了您所做的修改。然后您只需加入该新字段并更改您的选择语句以获取您想要的字段。

    【讨论】:

      【解决方案2】:

      您可以使用case 修改contract 的某些值。喜欢:

      select  prefix + ' ' + case contract
              when '1234' then 'ABC'
              when '5678' then 'XYZ'
              else contract
              end as prefix_plus_contract
      ,       *
      from    c
      join    p
      on      c.orders = p.orders
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-12
        • 2015-11-30
        • 2015-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多