尝试在两个 with 语句之后使用选择查询
Posted
技术标签:
【中文标题】尝试在两个 with 语句之后使用选择查询【英文标题】:Trying to use a select query after two with statements 【发布时间】:2021-12-31 00:10:11 【问题描述】:我计划用查询创建两个临时表,一个给出剩余贷款支付的总和,一个给出表中所有交易的总和。我已经用语句测试了这两个,它们可以自己工作,但是尝试使用它们执行选择查询似乎只会返回错误。
WITH RemainingLoans AS(SELECT SUM(TIMESTAMPDIFF(MONTH, l.NextPayment, l.FullPaymentConfirmed) * l.MonthlyPaymentRate) AS RemainingPayments FROM loans AS l);
WITH CurrentBalances AS(SELECT SUM(t.amount) AS allBalances FROM transactions AS t);
SELECT l.RemainingPayments - b.allBalances AS TotalOutstandings FROM RemainingLoans AS l, CurrentBalances AS b;
第一个称为 RemainingLoans,具有一个属性 RemainingPayments,第二个称为 CurrentBalances,具有一个属性 allBalances。据我所知,这些应该像表格一样工作,这就是为什么我在第三行尝试我的 select 子句,但是我目前遇到语法错误。有没有正确的方法来格式化我的 select 语句?
【问题讨论】:
您使用的是哪个版本的 mysql?SELECT version();
确切的错误是什么?将这两个细节都添加到问题中。
WITH 列表元素用逗号分隔。列表开头只有一个 WITH
关键字。分号位于整个语句的末尾,而不是 WITH
列表元素之后。
类似这样的东西:WITH RemainingLoans AS(SELECT SUM(TIMESTAMPDIFF(MONTH, l.NextPayment, l.FullPaymentConfirmed) * l.MonthlyPaymentRate) AS RemainingPayments FROM loans AS l) , CurrentBalances AS(SELECT SUM(t.amount) AS allBalances FROM transactions AS t) SELECT l.RemainingPayments - b.allBalances AS TotalOutstandings FROM RemainingLoans AS l, CurrentBalances AS b ;
谢谢您,这完全解决了问题。
@JonArmstrong 这应该是一个答案。
【参考方案1】:
这应该是一个语句,而不是多个语句。
The fiddle
WITH
列表元素用逗号分隔。列表开头只有一个 WITH
关键字。
分号位于整个语句的末尾,而不是WITH
列表元素之后。
这是调整后的声明:
WITH RemainingLoans AS (
SELECT SUM(TIMESTAMPDIFF(MONTH, l.NextPayment, l.FullPaymentConfirmed) * l.MonthlyPaymentRate) AS RemainingPayments
FROM loans AS l
)
, CurrentBalances AS (
SELECT SUM(t.amount) AS allBalances
FROM transactions AS t
)
SELECT l.RemainingPayments - b.allBalances AS TotalOutstandings
FROM RemainingLoans AS l
, CurrentBalances AS b
;
【讨论】:
以上是关于尝试在两个 with 语句之后使用选择查询的主要内容,如果未能解决你的问题,请参考以下文章
根据 with 子句中的条件选择要使用的 select 语句
无法运行两个单独的选择语句 Oracle / Toad ORA-00933