sql在不同列上左联接

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

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

  1. Proc sql;
  2. create table new_table_name as select
  3. a.proposal_code as new_name_proposal_code,
  4. a.1st_client_code as new_name_1st_client_code,
  5. a.2nd_client_code as new_name_2nd_client_code,
  6. a.3rd_client_code as new_name_3rd_client_code,
  7. a.4th_client_code as new_name_4th_client_code,
  8. a.product_type as new_name_product_type,
  9. b.2nd_client_code
  10. from existing_table a
  11. left join existing table b (on b.2nd_client_code=a.2nd_client_code and a.product_type = "clothes") or
  12. left join existing table b (on b.2nd_client_code=a.3rd_client_code and (a.product_type = "cars" or a.product_type = "bikes"));
  13. 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 不正确。您的查询还有其他问题。我想你想要:

  1. create table new_table_name as
  2. select a.proposal_code as new_name_proposal_code,
  3. a.1st_client_code as new_name_1st_client_code,
  4. a.2nd_client_code as new_name_2nd_client_code,
  5. a.3rd_client_code as new_name_3rd_client_code,
  6. a.4th_client_code as new_name_4th_client_code,
  7. a.product_type as new_name_product_type,
  8. coalsesce(bc.2nd_client_code, bcb.2nd_client_code)
  9. from existing_table a left join
  10. existing_table bc
  11. on bc.2nd_client_code = a.2nd_client_code and
  12. a.product_type = 'clothes' left join
  13. existing_table bcb
  14. on bcb.2nd_client_code = a.3rd_client_code and
  15. a.product_type in ('cars', 'bikes');

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

展开查看全部
hjqgdpho

hjqgdpho2#

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

  1. proc sql;
  2. create table new_table_name as
  3. select
  4. a.proposal_code as new_name_proposal_code
  5. ,a.client_code1 as new_name_client_code1
  6. ,a.client_code2 as new_name_client_code2
  7. ,a.client_code3 as new_name_client_code3
  8. ,a.client_code4 as new_name_client_code4
  9. ,a.product_type as new_name_product_type
  10. ,b.client_code2 as new_name_other_client_code2
  11. from tableA a
  12. left join tableB b
  13. on (b.client_code2=a.client_code2 and a.product_type = "clothes")
  14. or (b.client_code2=a.client_code3 and a.product_type in ("cars","bikes"))
  15. ;
  16. quit;

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

展开查看全部

相关问题