日期:2014-05-18 浏览次数:20474 次
--> 测试数据:[tbl] if object_id('[tbl]') is not null drop table [tbl] create table [tbl]([proname] varchar(2),[qty] int,[vtype] int,[optime] datetime) insert [tbl] select 'AA',-10,30,'2012-01-09' union all select 'AA',21,31,'2012-02-14' union all select 'AA',12,31,'2012-02-11' union all select 'AA',-2,30,'2012-03-11' union all select 'BB',-1,30,'2012-02-12' union all select 'BB',90,31,'2012-02-11' union all select 'BB',90,31,'2012-03-17' union all select 'BB',-6,30,'2012-02-19' select [proname],SUM(case when [vtype] = 31 THEN [qty] ELSE 0 END) as xsqty, SUM(CASE WHEN [vtype] = 30 THEN [qty] ELSE 0 END) AS xtqty, (select convert(varchar(10),max([optime]),120) from tbl b where a.proname=b.proname and [vtype] = 31) as lastxstime , (select convert(varchar(10),max([optime]),120) from tbl b where a.proname=b.proname and [vtype] = 30) as lastxstime from tbl a group by [proname] /* proname xsqty xtqty lastxstime lastxstime AA 33 -12 2012-02-14 2012-03-11 BB 180 -7 2012-03-17 2012-02-19 */ 你看看这个例子对你有没有帮助 我有点不怎么明白你的问题
------解决方案--------------------
-> 测试数据:[tbl] if object_id('[tbl]') is not null drop table [tbl] create table [tbl]([name] varchar(2),[logindate] date) insert [tbl] select 'a1','2011-1-2' union all select 'a1','2011-1-3' union all select 'a1','2011-1-4' union all select 'a1','2011-1-7' union all select 'a1','2011-1-12' union all select 'a1','2011-1-13' union all select 'a1','2011-1-16' union all select 'a2','2011-1-7' union all select 'a2','2011-1-8' union all select 'a2','2011-1-10' union all select 'a2','2011-1-11' union all select 'a2','2011-1-13' union all select 'a2','2011-1-24' with t as( select [name],[logindate],(select min(b.[logindate]) from tbl b where b.[logindate]>=a.[logindate] and b.name=a.name and not exists (select * from tbl c where c.[logindate]=dateadd(dd,1,b.[logindate]) and c.name=b.name)) as grp from tbl a ),m as( select [name],MIN([logindate]) as startdate,MAX(grp) as enddate from t group by grp,name ) select *,(DATEDIFF(DD,startdate,enddat