34,590
社区成员
发帖
与我相关
我的任务
分享
;WITH CTE AS(
SELECT T1.Item,SUM(T2.Qty)Qty,T1.TransDate TransDateStart,'每日结算'[Type]
,COUNT(T2.Item)RN
FROM A T1
JOIN A T2 ON T1.Item=T2.Item AND T1.TransDate>=T2.TransDate
GROUP BY T1.Item,T1.Qty,T1.TransDate
)
SELECT T3.Item,T3.Qty,DATEADD(DAY,T4.number,TransDateStart)TransDate,T3.[Type] FROM(
SELECT T1.*
,ISNULL(T2.TransDateStart,DATEADD(MONTH,1,DATEADD(DAY,1-DAY(T1.TransDateStart),T1.TransDateStart)))TransDateEnd
FROM CTE T1
LEFT JOIN CTE T2 ON T1.Item=T2.Item AND T1.RN+1=T2.RN
)T3
JOIN master..spt_values T4 ON T4.type='P'AND T4.number<DATEDIFF(DAY,TransDateStart,TransDateEnd)
ORDER BY T3.Item,TransDate
SQL2005+
IF OBJECT_ID('tempdb..#A')>0 DROP TABLE #A
IF OBJECT_ID('tempdb..#t')>0 DROP TABLE #t
GO
create table #A
(
Item nvarchar(20),
Qty numeric(16,2),
TransDate datetime,
[Type] nvarchar(10)
)
go
insert into #A values
('A001', '100.00', '2014/06/01', N'月初'),
('A001', '50.00', '2014/06/10', N'每天') ,
('A001', '-20.00', '2014/06/20', N'每天') ,
('B001', '200.00', '2014/06/01', N'月初') ,
('B001', '60.00', '2014/06/15', N'每天')
with cte as
(
select *,ROW_NUMBER()OVER(PARTITION BY Item order by TransDate)id
from #A
)
select *,
case
when datediff(day,TransDate,(select TransDate from cte where Item = a.Item and id = a.id+1)) is not null
then datediff(day,TransDate,(select TransDate from cte where Item = a.Item and id = a.id+1))
else datediff(day,TransDate,dateadd(day,-1,cast(DATEPART(YEAR,TransDate) as varchar(10))+right('-0'+cast(DATEPART(MM,TransDate)+1 as varchar(10)),3)+'-01' ))
end nb,
(select SUM(Qty) from cte where Item = a.Item and id <= a.id ) nqty
into #t
from cte a
;with cte as
(
select ROW_NUMBER()over(PARTITION by Item order by DATEADD(day,b.number,TransDate)) id,a.Item,a.nqty,newdate=DATEADD(day,b.number,TransDate) from #t a
join master..spt_values b on b.number< a.nb and b.type = 'P'
)
select * from cte
union all
select id,Item,nqty,dateadd(day,1,newdate) from cte a
where id = (select MAX(id) from cte where Item = a.Item)
order by Item,newdate
select
x.Item,
x.TransDate,
sum(y.Qty) as Qty,
'每日结算' as Type
from
(select
m.Item,dateadd(d,m.TransDate,n.id-1) as TransDate
from
A m,sysobjects n
where
datediff(m,m.TransDate,dateadd(d,m.TransDate,n.id-1))=0) x,
a y
where
x.Item=y.Item
and
x.TransDate>=y.TransDate
and
datediff(m, x.TransDate, y.TransDate)=0
group by
x.Item,x.TransDate
select
x.Item,
x.TransDate,
sum(y.Qty) as Qty,
'每日结算' as Type
from
(select
m.Item,dateadd(d,m.TransDate,n.id-1) as TransDate
from
A m,sysobjects n
where
datediff(m,m.TransDate,dateadd(d,m.TransDate,n.id-1))=0) x,
a y
where
x.Item=y.Item
and
x.TransDate>=y.TransDate
and
datediff(m.x.TransDate,y.TransDate)=0
group by
x.Item,x.TransDate