【问题标题】:Concatenate Subqueries with Unions (one table with two condition)用联合连接子查询(一个表有两个条件)
【发布时间】: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。日期过滤器没有意义,你的意思是&gt;= and &lt;。无需在外部查询中使用group by AR,因为无论如何它们只是两个不同的值。像这样指定日期文字 '20201231'
  • 谢谢@GordonLinoff
  • 谢谢@Charlieface

标签: sql join subquery conditional-statements union


【解决方案1】:

您可以按如下方式使用条件聚合:

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,并且它用于除法,因此请在此处使用适当的逻辑。

【讨论】:

  • 谢谢@Popeye
  • 如果它解决了你的问题,你可以考虑接受这个答案。
  • 嗨兄弟,你能帮帮我吗,我有一个关于日期和时间的案例。 stackoverflow.com/questions/65712954/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 2016-08-07
  • 2015-10-08
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多