日期:2014-05-17  浏览次数:20529 次

在线求一个SQL语句~~~~ 有关累计的
我有一个表,  要全部生成结果,  如果能用一个SQL语句搞定最好,



其中:
从vip第一次消费记录的每个月都要生成,  比如A 2013年1月份开始消费, 2月份没消费, 2月份也要出来, 
B从2月份开始消费, 那记录就从2月份开始



这是原始表语句:

create table #xs(vip varchar(20), date datetime, sale float)
insert into #xs(vip, date, sale)
select 'A' as vip,'2013-1-1' as date, 230 as sale union all
select 'A','2013-1-5', 400 union all
select 'A','2013-3-6', 500 union all
select 'A','2013-4-30',600 union all
select 'B','2013-2-3',200 union all
select 'B','2013-3-5',300 union all
select 'B','2013-4-24',400 

select * from #xs

------解决方案--------------------
要是动态的,一条语句有点儿费劲!
1、要拼接出每个会员从开始消费月份到结束消费月的的所有月份。
2、然后左连接计算出每月消费次数
3、递归计算累计数
------解决方案--------------------
多久每消费可以这个[code=sql]select datediff (DAY ,date,DATEADD(MONTH, 1, date - DAY(date) + 1) - 1) as 多久没消费 from #xs[code]
------解决方案--------------------

if object_id('tempdb..#xs') is not null
drop table #xs;

create table #xs(vip varchar(20), date datetime, sale float)
insert into #xs(vip, date, sale)
select 'A' as vip,'2013-1-1' as date, 230 as sale union all
select 'A','2013-1-5', 400 union all
select 'A','2013-3-6', 500 union all
select 'A','2013-4-30',600 union all
select 'B','2013-2-3',200 union all
select 'B','2013-3-5',300 union all
select 'B','2013-4-24',400 

;with t as 
(
select dateadd(month, number,'20130101') MonthDay
from master.dbo.spt_values
where type='p'
)
,tRange as 
(
select vip,convert(varchar(6),min(date),112)+'01' MinMonth,convert(varchar(6),max(date),112)+'01' MaxMonth
from #xs
group by vip
),tDimDate as
(
select tr.vip,t.MonthDay StartDay,dateadd(d,-1,DATEADD(month,1,t.MonthDay)) EndDay
from tRange tr
join t 
on tr.MinMonth<=t.MonthDay
and tr.MaxMonth>=t.MonthDay
),tdata as (
select t.vip,EndDay
,DATEDIFF(d,(select top 1 date from #xs xs where xs.date <=t.EndDay and xs.vip=t.vip&nbs