日期:2014-05-18 浏览次数:20495 次
proname qty vtype optime AA -10 30 2012-01-09 AA 21 31 2012-02-14 AA 12 31 2012-02-11 AA -2 30 2012-03-11 BB -1 30 2012-02-12 BB 90 31 2012-02-11 BB 90 31 2012-03-17 BB -6 30 2012-02-19
proname xssl xtsl lastxstime lastxttime 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]([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
*/