我的 SQL 有问题。我习惯于在 SAS 中进行编码,并能够创建中间表来执行操作/修改。 除了我必须在 Oracle 数据库上使用 SQL Developer,并使用单个查询。
我想将 2 个查询(如下)合并为一个,使用 INNER JOIN 从 2 个表中检索公共行和变量作为最终输出。
我真的不知道该怎么做。谢谢您的帮助。
问题1:
select A.*, B.var1, B.var2, B.var3, B.var4, B.var5, B.var6 as new_var6, B.var7,
case
when a.var1 = 'thing' then CONCAT(B.var4,A.var1)
else CONCAT(b.var7,A.var1)
end as key_second_join,
1 as var8
from bibliotheque.BASE_A A
inner join bibliotheque.BASE_B B
on A.key_first_join = B.var1
order by A.key_first_join;
问题2:
SELECT T.*, CONCAT(C_VAR1,C_VAR3) key_second_join
FROM (
SELECT *
FROM bibliotheque2.BASE_C
WHERE (C_VAR1, C_VAR2) IN (
SELECT C_VAR1, MAX(C_VAR2)
FROM bibliotheque2.BASE_C
GROUP BY C_VAR1)) T;
我尝试过一个大型查询,但总是收到如下错误:“缺少右括号”、“列定义不明确”
大查询的目标是得到这样的结果:
select *
from query1 as t2
inner join query2 as t1 on t1.key_second_join=t2.key_second_join;
run;
为表(或您的情况下的子查询)添加别名时,不需要单词
as
。下面的示例查询应该可以工作。
SELECT *
FROM (SELECT a.*,
b.var1,
b.var2,
b.var3,
b.var4,
b.var5,
b.var6 AS new_var6,
b.var7,
CASE WHEN a.var1 = 'thing' THEN CONCAT (b.var4, a.var1) ELSE CONCAT (b.var7, a.var1) END AS key_second_join,
1 AS var8
FROM bibliotheque.base_a a INNER JOIN bibliotheque.base_b b ON a.key_first_join = b.var1) t2
JOIN (SELECT t.*, CONCAT (c_var1, c_var3) key_second_join
FROM (SELECT *
FROM bibliotheque2.base_c
WHERE (c_var1, c_var2) IN ( SELECT c_var1, MAX (c_var2)
FROM bibliotheque2.base_c
GROUP BY c_var1)) t) t1
ON (t1.key_second_join = t2.key_second_join);