使用子查询重写 OUTER APPLY 到 Redshift
Rewrite OUTER APPLY to Redshift with subquery
我将 sql 服务器脚本重写为 redshift 数据库查询
我有 OUTER APPLY 构造
OUTER APPLY
(
SELECT q.*
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY ca.Id DESC) AS rn,
ca.StateProvince,
ca.ZipPostalCode,
ca.ContactId
FROM public.contact_addresses ca
WHERE ca.OrganizationId = <Parameters.DemographicsOrgId>
AND ca.DeletedDate IS NULL
AND ca.TypeId = 7
AND ca.ContactId = cc.Id
) q
WHERE q.rn = 1
) ca
但是Redshift没有外部应用。如何用 LEFT JOIN 正确重写它?
更新
我考虑改写成这样
LEFT JOIN
(
SELECT q.*,
q.rn = 1
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY ca.Id DESC) AS rn,
ca.StateProvince,
ca.ZipPostalCode,
ca.ContactId
FROM public.contact_addresses ca
WHERE ca.OrganizationId = <Parameters.DemographicsOrgId>
AND ca.DeletedDate IS NULL
AND ca.TypeId = 7
AND ca.ContactId = cc.Id
) q
GROUP BY q.rn
) ca
ON ca.rn = 1
但这正确吗?
OUTER APPLY 运算符 returns 从左 table 表达式开始的所有行,而不管其是否与右 table 表达式匹配。对于那些在右 table 表达式中没有对应匹配项的行,它在右 table 表达式
的列中包含 NULL 值
所以你的做法是正确的
不,它看起来不对。我猜:
LEFT JOIN
(SELECT ca.OrganizationId,
ROW_NUMBER() OVER (ORDER BY ca.Id DESC) AS rn,
ca.StateProvince,
ca.ZipPostalCode,
ca.ContactId
FROM public.contact_addresses ca
WHERE ca.DeletedDate IS NULL AND
ca.TypeId = 7
GROUP BY ca.OrganizationId, ca.ContactId
) ca
ON ca.ContactId = cc.ID AND
ca.OrganizationId = <Parameters.DemographicsOrgId> AND
ca.rn = 1
基本上,您需要根据相关条件(如果它们相等)进行聚合,然后将它们用于外部 ON
条件。
我将 sql 服务器脚本重写为 redshift 数据库查询
我有 OUTER APPLY 构造
OUTER APPLY
(
SELECT q.*
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY ca.Id DESC) AS rn,
ca.StateProvince,
ca.ZipPostalCode,
ca.ContactId
FROM public.contact_addresses ca
WHERE ca.OrganizationId = <Parameters.DemographicsOrgId>
AND ca.DeletedDate IS NULL
AND ca.TypeId = 7
AND ca.ContactId = cc.Id
) q
WHERE q.rn = 1
) ca
但是Redshift没有外部应用。如何用 LEFT JOIN 正确重写它?
更新
我考虑改写成这样
LEFT JOIN
(
SELECT q.*,
q.rn = 1
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY ca.Id DESC) AS rn,
ca.StateProvince,
ca.ZipPostalCode,
ca.ContactId
FROM public.contact_addresses ca
WHERE ca.OrganizationId = <Parameters.DemographicsOrgId>
AND ca.DeletedDate IS NULL
AND ca.TypeId = 7
AND ca.ContactId = cc.Id
) q
GROUP BY q.rn
) ca
ON ca.rn = 1
但这正确吗?
OUTER APPLY 运算符 returns 从左 table 表达式开始的所有行,而不管其是否与右 table 表达式匹配。对于那些在右 table 表达式中没有对应匹配项的行,它在右 table 表达式
的列中包含 NULL 值所以你的做法是正确的
不,它看起来不对。我猜:
LEFT JOIN
(SELECT ca.OrganizationId,
ROW_NUMBER() OVER (ORDER BY ca.Id DESC) AS rn,
ca.StateProvince,
ca.ZipPostalCode,
ca.ContactId
FROM public.contact_addresses ca
WHERE ca.DeletedDate IS NULL AND
ca.TypeId = 7
GROUP BY ca.OrganizationId, ca.ContactId
) ca
ON ca.ContactId = cc.ID AND
ca.OrganizationId = <Parameters.DemographicsOrgId> AND
ca.rn = 1
基本上,您需要根据相关条件(如果它们相等)进行聚合,然后将它们用于外部 ON
条件。