【发布时间】:2021-04-12 19:28:52
【问题描述】:
我有 1 张桌子,有 2 种不同的条件。 我要呈现 AR,年度,AR / 年度 * 365。
下面的代码可以运行
select AR, AR*365
from (select sum(total_amount) AR
from invoices
where issue_date is not null and closed_at is null
and issue_date <= 'January 1,2020' and issue_date <DATEADD (DAY, 1, 'December 31,2020')
UNION
select sum(total_amount)
from invoices
where closed_at <= 'January 1,2020' and closed_at <DATEADD (DAY, 1, 'December 31,2020')
)x group by AR;
结果:
AR
1,895.23 15,903,040.94
691,758.95 5,804,609,943.1
然后我想显示 AR、年度、AR/annual*365 但出现错误:
select AR, annual, AR/annual*365 from
(select sum(total_amount) AR
from invoices
where issue_date is not null and closed_at is null
and issue_date <= 'January 1,2020' and issue_date <DATEADD (DAY, 1, 'December 31,2020')
UNION
select sum(total_amount) annual
from invoices
where closed_at <= 'January 1,2020' and closed_at <DATEADD (DAY, 1, 'December 31,2020'))x group by
AR;
当你想显示“年度”的年度值时,第一行/第一次选择无法读取...
但是当我们从第一行删除“annual”时,可以读取annual。
我希望读取第一行/第一个选择中的“年度”,以便可以使用其他值进行计算。
有人知道怎么解决吗?
【问题讨论】:
-
请提供样本数据、期望的结果、适当的数据库标签,并清楚说明您想要做什么。
-
我想你想
cross join这两个结果而不是union。这样您就可以同时访问这两个值。除此之外,您遇到的其他问题是:union将区分并删除相同的结果,您想要union all。日期过滤器没有意义,你的意思是>= and <。无需在外部查询中使用group by AR,因为无论如何它们只是两个不同的值。像这样指定日期文字'20201231' -
谢谢@GordonLinoff
-
谢谢@Charlieface
标签: sql join subquery conditional-statements union