オラクルがすべての面倒な作業を行うようにコードを変更しようとしています。もともと、私は次のことを行う関数を持っていました:
<!--- get common data --->
<cfquery name="getCommon">
SELECT x, NVL(SUM(y), 0) as y
FROM table_1
WHERE z between #this# and #that#
GROUP BY x
</cfquery>
<!--- place common values into a struct --->
<cfset oCommon = StructNew() >
<cfloop query="getCommon">
<cfset oCommon[x] = y >
</cfloop>
<!--- get records to loop through --->
<cfquery name="getSomething">
SELECT a, b, c/d as e from (
SELECT DISTINCT t2.a,
t2.b,
c,
sum(d)as d
FROM table_2 t2
LEFT JOIN table_3 t3
ON t2.a = t3.a
AND t2.b = t3.b
GROUP BY t2.a, t2.b, c
)
</cfquery>
<!--- loop through the results --->
<cfloop query="getSomething">
<!--- do an update to the target table if conditions are met --->
<!--- calculate my important new value --->
<cfset new_value = #getSomething.e# * #oCommon[b]# >
<!--- finally, insert my new values into the target table --->
<cfquery name="insertTarget">
INSERT INTO target_table(
a,
b,
c
)
VALUES (
#getSomething.a#,
#getSomething.b#,
#new_value#
)
</cfquery>
</cfloop>
Oracle の MERGE を使用してループ内の update ステートメントを置き換える方法は既に理解しています。私の問題は、insert ステートメントを置き換える SQL です。SQL内で新しい値を計算できるようにしたいのですが...それができたら、MERGE/挿入部分をかなり簡単に把握できると思います。
だから私は次のようなことをしたい:
SELECT a, b, c/d*y as e from (
SELECT DISTINCT t2.a,
t2.b,
c,
sum(d)as d,
(
SELECT y FROM (
SELECT x, NVL(SUM(y), 0) as y
FROM table_1
WHERE z between #this# and #that#
AND x = t2.a
GROUP BY x
)
)
FROM table_2 t2
LEFT JOIN table_3 t3
ON t2.a = t3.a
AND t2.b = t3.b
GROUP BY t2.a, t2.b, c
)
これはおそらく明らかに機能しません。現在、私は ORA-00904: "t2"."a": Invalid Identifier を取得していますが、これは驚くべきことではありません。
したがって、基本的には、x = table_2.a によって関連付けられた table_1 から y の合計を元の getSomething クエリに取得する方法を理解する必要があります。
編集:これを試しましたが、正しくありません:
SELECT a, b, c/d*y as e from (
SELECT DISTINCT t2.a,
t2.b,
c,
sum(d)as d,
NVL(SUM(y), 0) as y
FROM table_2 t2
LEFT JOIN table_3 t3
ON t2.a = t3.a
AND t2.b = t3.b
LEFT JOIN table_1 t1
ON t1.x = t2.a
AND t1.z between #this# and #that#
GROUP BY t2.a, t2.b, c
)