我有两个查询:
查询1:
select afp,
max(fecha) as fecha
from valcuota
where afp ='MODELO'
UNION
select afp,
date(max(fecha),'-31 days') as fecha
from valcuota
where afp ='MODELO'
查询2
select strftime('%m-%Y',periodo) as periodo_str, fondo,periodo
from (select fondo, periodo
from movimientos
group by fondo , periodo
order by count(periodo) desc
) temp where temp.fondo = fondo
group by periodo_str
order by periodo desc
limit 2
并且我需要以这样的方式将它们加入:query1.fecha的最早和最新日期与query2.periodo相关联
这就是我需要的
答案 0 :(得分:0)
在每个查询中使用ROW_NUMBER()
创建一个公共列,您可以在这些列上加入它们:
select
t2.periodo_str, t2.fondo, t2.periodo, t1.afp, t1.fecha
from (
select t.*, row_number() over (order by t.fecha) rn
from (
select afp,
max(fecha) as fecha
from valcuota
where afp ='MODELO'
UNION
select afp,
date(max(fecha),'-31 days') as fecha
from valcuota
where afp ='MODELO'
) t
) t1 inner join (
select t.*, row_number() over (order by t.periodo) rn
from (
select strftime('%m-%Y',periodo) as periodo_str, fondo,periodo
from (
select fondo, periodo
from movimientos
group by fondo, periodo
order by count(periodo) desc
) temp where temp.fondo = fondo
group by periodo_str
order by periodo desc
limit 2
) t
) t2 on t2.rn = t1.rn