雪花中的相关子查询
Posted
技术标签:
【中文标题】雪花中的相关子查询【英文标题】:Correlated Sub Queries in Snowflake 【发布时间】:2020-10-15 22:33:42 【问题描述】:请告诉我如何将下面的 sql server 代码转换为 Snowflake,因为 Snowflake 没有 支持相关子查询。
SELECT DISTINCT
CURRENT_DATE as creationdate, LastName,
(SELECT Date AS Exp1
FROM PSU AS P
WHERE (HQL = a.B1L) AND (HQH = a.B1H) AND
(HQN =
(SELECT MAX(HQN) AS Exp1
FROM PSU AS P2
WHERE (HQL = a.B1L) AND (HQH = a.B1H) AND (HQZ = 'P') AND (HQF = 'P'))))AS "paymentDATE",
(CASE WHEN (SELECT MAX(H6P)
FROM sss
WHERE H6P = B1L AND H6CPS NOT IN ('H', 'C')) IS NULL THEN 'N' ELSE 'Y' END)
AS "ORDER(Y/N)"
FROM ACT AS a INNER JOIN
CU AS c ON c.BSL = a.B1L INNER JOIN
CS AS cs ON cs.B2L = a.B1L AND a.B1H = cs.B2H
WHERE (a.B1M <> 0) AND (cs.B2K IN ('H'))
我为上述代码创建的雪花代码,我还没有为“ORDER(Y/N)”字段创建 CTE:我觉得 CTE 中的连接不正确,不确定如何将 CTE 连接到 main查询
WITH RECURSIVE PaymentDate AS
(SELECT MAX(HQN) AS Expr1
FROM PSU AS P2
JOIN POP AS a ON (P2.HQL = a.B1L) AND (P2.HQH= a.B1H) AND (P2.HQZ = 'P') AND
(P2.HQF= 'P')
)
, LPD AS
(SELECT Date as Exp1 FROM
PSU AS P
JOIN ACT AS A ON (P.HQL = a.B1L) AND (P.HQH = a.B1H)
JOIN TNR ON (P.HQN =TNR.Expr1)
)
SELECT DISTINCT CURRENT_DATE as creationdate, LastName
(CASE WHEN (SELECT MAX(H6P) FROM sss WHERE H6P = B1L AND H6CPS NOT IN
('H', 'C'))
IS NULL THEN 'N' ELSE 'Y' END) AS "ORDER(Y/N)"
FROM ACT AS a INNER JOIN
CU AS c ON c.BSL = a.B1L
INNER JOIN CS AS cs ON cs.B2L = a.B1L AND a.B1H = cs.B2H
WHERE (a.B1M <> 0) AND (cs.B2K IN ('H'))
【问题讨论】:
【参考方案1】:如果您将两个子查询都重写为应该可以工作的 CTE。
第一个 CTE 获取这些值: HQL, HQH, MAX(HQN)
第二个 CTE 将 PSU 加入第一个 CTE 以获得“paymentDATE”
将第二个 CTE 加入您的主查询
【讨论】:
感谢尼克,您的评论。我创建了 CTE,但我缺少连接中的一些位置...请您创建 SF 代码并显示它。 为了能够编写实际代码,我需要能够对其进行测试。如果您希望我这样做,请提供表创建脚本、示例数据和预期结果数据集。或者,如果您提供您的 CTE SQL,我可以检查它是否存在可能的问题 尼克,我添加了我在问题中创建的 SF 代码。我试图将代码粘贴到评论部分,但它说字符超出,所以我添加了问题。能否请您更正代码并将SF代码发送给我。以上是关于雪花中的相关子查询的主要内容,如果未能解决你的问题,请参考以下文章