日期:2014-05-18  浏览次数:20393 次

含有多重含义字段的纵横表切换,增加难度
TA表如下:商品销售和退货在一起,用vtype区别:30表示退货,31表示销售 ,optime标示操作时间
 
HTML code
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


要求列出商品最近一次的销售数量,退货数量极其最近一次销售、退货时间

HTML code
proname   xssl    xtsl  lastxstime   lastxttime
 AA       33      -12   2012-02-14   2012-03-11
 BB       180     -7    2012-03-17   2012-02-19


... 


------解决方案--------------------
SQL code

--> 测试数据:[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
*/