用联合连接子查询(一个 table 有两个条件)
Concatenate Subqueries with Unions (one table with two condition)
我有 1 个 table 具有 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"的年值时第一个line/firstselect无法读取...
但是当我们删除第一行的“annual”时,annual 可以读取。
我想读取第一行/第一个 select 的“年度”,以便可以用其他值计算它。
有人知道怎么解决吗?
您可以按如下方式使用条件聚合:
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, 1, 'December 31,2020')
then total_amount end) as annual
from invoices) t
有可能 annual
是 0 并且它被用在除法中所以在那里使用适当的逻辑。
我有 1 个 table 具有 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"的年值时第一个line/firstselect无法读取...
但是当我们删除第一行的“annual”时,annual 可以读取。
我想读取第一行/第一个 select 的“年度”,以便可以用其他值计算它。
有人知道怎么解决吗?
您可以按如下方式使用条件聚合:
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, 1, 'December 31,2020')
then total_amount end) as annual
from invoices) t
有可能 annual
是 0 并且它被用在除法中所以在那里使用适当的逻辑。