34,838
社区成员




with
cte1 as
(
select '201501' F_Month union all
select '201502' F_Month union all
select '201503' F_Month union all
select '201504' F_Month union all
select '201505' F_Month
),
cte2 as
(
select '201501' F_Month, '001' F_Shopid, '003001' F_SupplierID, '0030' F_FatherSupplierID union all
select '201503' F_Month, '001' F_Shopid, '003002' F_SupplierID, '0030' F_FatherSupplierID
)
select aa.F_Month, bb.F_Shopid, bb.F_SupplierID, bb.F_FatherSupplierID from
(select cte1.F_Month, MAX(cte2.F_Month) F_MonthMax from cte1 left join cte2 on cte1.F_Month>=cte2.F_Month group by cte1.F_Month) aa
left join cte2 bb on aa.F_MonthMax=bb.F_Month
create table #tmpMonth
(
f_Month nvarchar(50)
)
CREATE TABLE #tmp1(
[F_ShopID] [nvarchar](50) NOT NULL,
[F_Month] [nvarchar](50) NOT NULL,
[F_FatherSupplierId] [nvarchar](50) NOT NULL,
[F_SupplierId] [nvarchar](50) NOT NULL
)
insert #tmpMonth values('201501')
insert #tmpMonth values('201502')
insert #tmpMonth values('201503')
insert #tmpMonth values('201504')
insert #tmpMonth values('201505')
insert #tmpMonth values('201506')
insert #tmpMonth values('201507')
insert #tmpMonth values('201508')
insert #tmp1 values('0001','201501','0028','002801')
insert #tmp1 values('0001','201503','0028','002804')
insert #tmp1 values('0001','201504','0028','002804')
insert #tmp1 values('0001','201506','0028','002803')
select
t1.F_month
,t2.F_ShopID
,t2.F_FatherSupplierID
,t2.F_SupplierID
from #tmpMonth t1
left join #tmp1 t2
on t2.f_month = (select max(f_month) from #tmp1 t3 where t3.f_month <= t1.f_month)
drop table #tmpMonth
drop table #tmp1