sql在不同列上左联接

pw136qt2  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(236)

我相信这很容易。刚刚开始使用sql,所以我觉得有点棘手。因此,我在sas上使用sql,我想根据一个列的值连接两个表,但在不同的列上。示例:

Proc sql;
create table new_table_name as select 
a.proposal_code as new_name_proposal_code,
a.1st_client_code as new_name_1st_client_code,
a.2nd_client_code as new_name_2nd_client_code,
a.3rd_client_code as new_name_3rd_client_code,
a.4th_client_code as new_name_4th_client_code,
a.product_type as new_name_product_type,
b.2nd_client_code
from existing_table a
left join existing table b (on b.2nd_client_code=a.2nd_client_code and a.product_type = "clothes") or 
left join existing table b (on b.2nd_client_code=a.3rd_client_code and (a.product_type = "cars" or a.product_type = "bikes"));
quit;

这就是我目前使用的代码,目标是使用b.2nd client code=a连接表a和表b。如果表a中的产品类型是=to“clothing”,那么使用b.2nd client code=a.2nd client code连接表a和表b。如果表a中的产品类型是“cars”或“bikes”,那么使用b.2nd client code=a.3rd client code连接表a和表b。基本上,看两个不同的“关于”的具体产品类型。当连接这两个表时,如果一行有产品类型“衣服”,我希望它看第二个客户机代码,如果它是“汽车”或“自行车”,看第三个客户机代码。
希望我说清楚。我现在犯的错误是“期待一个成功”。是语法问题吗?

ntjbwcob

ntjbwcob1#

对。前面的括号 on 不正确。您的查询还有其他问题。我想你想要:

create table new_table_name as
    select a.proposal_code as new_name_proposal_code,
           a.1st_client_code as new_name_1st_client_code,
           a.2nd_client_code as new_name_2nd_client_code,
           a.3rd_client_code as new_name_3rd_client_code,
           a.4th_client_code as new_name_4th_client_code,
           a.product_type as new_name_product_type,
           coalsesce(bc.2nd_client_code, bcb.2nd_client_code)
    from existing_table a left join
         existing_table bc
         on bc.2nd_client_code = a.2nd_client_code and
            a.product_type = 'clothes' left join 
         existing_table bcb
         on bcb.2nd_client_code = a.3rd_client_code and
            a.product_type in ('cars', 'bikes');

笔记:
前面没有括号 on 条款。
or left join . or 是布尔运算符。 left join 是集(即表和结果集)上的运算符。不要混在一起。
没有重复的表别名。
你想把这两个代码结合起来,所以你需要 coalesce()select .
字符串的sql分隔符是单引号,而不是双引号。 in 比一串 or 条件。

hjqgdpho

hjqgdpho2#

听起来你只是想要一个复杂的标准,而不是两个连接。像这样:

proc sql;
create table new_table_name as 
select 
   a.proposal_code as new_name_proposal_code
  ,a.client_code1 as new_name_client_code1
  ,a.client_code2 as new_name_client_code2
  ,a.client_code3 as new_name_client_code3
  ,a.client_code4 as new_name_client_code4
  ,a.product_type as new_name_product_type
  ,b.client_code2 as new_name_other_client_code2
from tableA a
left join tableB b
  on (b.client_code2=a.client_code2 and a.product_type = "clothes")
  or (b.client_code2=a.client_code3 and a.product_type in ("cars","bikes"))
;
quit;

为了得到更好的答案,请张贴示例输入和所需输出。

相关问题