使用CTE

时间:2019-03-12 13:53:33

标签: sql common-table-expression

我有两个查询

查询1:从“日期维度”输出中检索月份的最后两个月末日期为

ActualDate
28-02-2019
30-01-2019

查询2:在where子句中使用日期字段...

E.g. All the data at Date D1. 

如何在查询2中递归使用查询1的输出,这样

总输出应为

All Data at Date "28-02-2019" Unionall 
All Data at Date "30-01-2019"

任何帮助将不胜感激。

简而言之,查询2如下,我想通过更改实际日期通过递归CTE获得该查询最近3个月的结果

select     SL.InvoiceID, 
           sum(SL.Balance) as Balance,

    from FactableBalance as SL
    inner join DateDimension as DT1 
       on DT1.ActualDate = '2019-02-28 00:00:00.000'
    where SL.LedgerAccountType = 'Credit'
      and DT1.ID >= BalanceOpenDateID
      and DT1.ID < BalanceCloseDateID 
    group by SL.InvoiceID

2 个答案:

答案 0 :(得分:0)

尝试如下

   with cte1
    as
    (select * from query1
    ), cte2 as
    (
    select * from query2
    ) select * from cte1 union all
    select * from cte2

答案 1 :(得分:0)

您似乎想要这样的东西:

with dates as (
      . . .
     )
select . . .
from dates left join
     <something goes here> s
     on s.<whatever> ? d.date

这有点模糊,但是您可以使用join来“填写”您要查找的比较。