如何解决用联合连接子查询一张表有两个条件
我有 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,2020')
)x group by AR;
结果:
AR
1,895.23 15,903,040.94
691,758.95 5,804,609,943.1
然后我想显示 AR、Annual、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')
UNION
select sum(total_amount) annual
from invoices
where closed_at <= 'January 1,2020'))x group by
AR;
当你想显示“年”的年值第一行/第一次选择无法读取...
但是当我们删除第一行中的“annual”时可以读取years。
我希望读取第一行/第一个选择中的“年度”,以便可以使用其他值进行计算。
有人知道怎么解决吗?
解决方法
您可以按如下方式使用条件聚合:
Select AR,annual,AR/annual*365 from
(select sum(case when 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')
then total_amount end) AR,sum(case when closed_at <= 'January 1,2020'
and closed_at <DATEADD (DAY,2020')
then total_amount end) as annual
from invoices) t
annual
可能为 0 并且用于除法,因此请在此处使用适当的逻辑。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。