declare @ table(商品编号 char(4),数量 int,标志 int)
insert @ values('0101',      500      ,1)
insert @ values('0102' ,     1000    , 0)
insert @ values('0411'  ,    800      ,1)
insert @ values('1121'   ,   2000    , 1)
insert @ values('3201'    ,  400    ,  0)
insert @ values('3308'     , 600   ,   1)
insert @ values('3308'      ,10000,    0)declare @1 table(编号 char(4),名称 varchar(100),开始商品编号 char(4),截止商品编号 char(4))
insert @1 values('0001',      'AAAAA'       ,    '0101'         , '0299')
insert @1 values('0002' ,     'BBBBB'        ,   '0301'        ,  '0499')
insert @1 values('0002'  ,    'BBBBB'         ,  '3301'       ,   '3399')
insert @1 values('0003'   ,   'CCCCC'          , '3201'      ,    '3299')
select 名称 大类商品,(select sum(数量) from @ where 标志=1 and 商品编号 between min(aa.开始商品编号) and max(aa.截止商品编号)),
(select sum(数量) from @ where 标志=0 and 商品编号 between min(aa.开始商品编号) and max(aa.截止商品编号))
 from @1 aa  group by 名称

解决方案 »

  1.   

    大力兄,
        不行啊,比如BBBBB并没有包含0301-3399之间全部数据,其中0500-3299间可能属于大类DDDDD。如果那样,BBBBB的汇总数据就不对了    怎么办呢
      

  2.   

    declare @ table(商品编号 char(4),数量 int,标志 int)
    insert @ values('0101',      500      ,1)
    insert @ values('0102' ,     1000    , 0)
    insert @ values('0411'  ,    800      ,1)
    insert @ values('1121'   ,   2000    , 1)
    insert @ values('3201'    ,  400    ,  0)
    insert @ values('3308'     , 600   ,   1)
    insert @ values('3308'      ,10000,    0)declare @1 table(编号 char(4),名称 varchar(100),开始商品编号 char(4),截止商品编号 char(4))
    insert @1 values('0001',      'AAAAA'       ,    '0101'         , '0299')
    insert @1 values('0002' ,     'BBBBB'        ,   '0301'        ,  '0499')
    insert @1 values('0002'  ,    'BBBBB'         ,  '3301'       ,   '3399')
    insert @1 values('0003'   ,   'CCCCC'          , '3201'      ,    '3299')select 名称,sum(case when 标志=1 then 数量 else 0 end),sum(case when 标志=0 then 数量 else 0 end) from @ join @1 on 商品编号>=开始商品编号 and 商品编号<=截止商品编号 group by 名称
      

  3.   

    declare @ table(商品编号 char(4),数量 int,标志 int)
    insert @ values('0101',      500      ,1)
    insert @ values('0102' ,     1000    , 0)
    insert @ values('0411'  ,    800      ,1)
    insert @ values('1121'   ,   2000    , 1)
    insert @ values('3201'    ,  400    ,  0)
    insert @ values('3308'     , 600   ,   1)
    insert @ values('3308'      ,10000,    0)declare @1 table(编号 char(4),名称 varchar(100),开始商品编号 char(4),截止商品编号 char(4))
    insert @1 values('0001',      'AAAAA'       ,    '0101'         , '0299')
    insert @1 values('0002' ,     'BBBBB'        ,   '0301'        ,  '0499')
    insert @1 values('0002'  ,    'BBBBB'         ,  '3301'       ,   '3399')
    insert @1 values('0003'   ,   'CCCCC'          , '3201'      ,    '3299')select 名称,sum(case when 标志=1 then 数量 else null end) 为1的和,sum(case when 标志=0 then 数量 else null end) 为0的和 from @ join @1 on 商品编号>=开始商品编号 and 商品编号<=截止商品编号 group by 名称