--测试数据create table tb(编号 char(4),大类 varchar(10),小类 varchar(10),型号 varchar(10),数量 int,单价 decimal(10,2),单位 varchar(10))
insert tb select '0001','有价卡','充值卡','50元' ,300,1.25,'伟达'
union all select '0002','有价卡','充值卡','100元',80 ,1.5 ,'伟达'
union all select '0002','有价卡','充值卡','100元',300,1.5 ,'通大'
union all select '0002','有价卡','充值卡','100元',100,1.5 ,'通大'
union all select '0001','有价卡','充值卡','50元' ,100,1.25,'通大'
go--查询处理
declare @s nvarchar(4000),@i varchar(10)
select @s='',@i=max(cnt)
from(select 单位,cnt=count(distinct 编号) from tb group by 单位)a
while @i>0
select @s=',数量'+@i+'=isnull(sum(case id when '+@i+' then 数量 end),0)'
+',单价'+@i+'=isnull(max(case id when '+@i+' then 单价 end),0)'
+@s
,@i=@i-1
exec('select 单位'+@s+'
from(
select 单位,数量,单价,id=(select count(distinct 编号) from tb where 单位=aa.单位 and 编号<=aa.编号)
from tb aa
)a group by 单位')
go--删除测试
drop table tb/*--结果单位         数量1         单价1          数量2         单价2          
---------- ----------- ------------ ----------- ------------ 
通大         100         1.25         400         1.50
伟达         300         1.25         80          1.50
--*/

解决方案 »

  1.   

    我自己的方法,只能得到这个样子,如下:请指教:
    declare @sql varchar(8000)
    declare @s varchar(8000)
    declare @s1 varchar(8000)
    set @sql=''
    set @sql='select 单位'
    select @sql=@sql+',['+编号+']=(case 编号 when '''+编号+''' then 数量 else 0 end)'
    from (select distinct 编号 from tradesman_view) a
    set @sql=@sql+'from tb'
    set @s='select 单位'
    select @s=@s+',sum(['+编号+']) as ['+编号+']'
    from (select distinct 编号 from tb) a
    set @s=@s+'from ('+@sql+')b group by 单位'
    exec(@s)
    结果:
    单位     0001     0002      0004
    天音 0 0 100
    通大 100 400 0
    伟达 300 80 200
      

  2.   

    我的妈亲呢!
    不管邹大侠的对否,他的这种方法我是从未见过的!!!!!!!
    太让我感慨了~我还感觉自已SQL学的够可以的了,差太多了,无地自容!
      

  3.   

    create table tb(编号 char(4),大类 varchar(10),小类 varchar(10),型号 varchar(10),数量 int,单价 decimal(10,2),单位 varchar(10))
    insert tb select '0001','有价卡','充值卡','50元' ,300,1.25,'伟达'
    union all select '0002','有价卡','充值卡','100元',80 ,1.5 ,'伟达'
    union all select '0002','有价卡','充值卡','100元',300,1.5 ,'通大'
    union all select '0002','有价卡','充值卡','100元',100,1.5 ,'通大'
    union all select '0001','有价卡','充值卡','50元' ,100,1.25,'通大'
    go--查询处理
    declare @s varchar(8000),@i as int
    set @s=''
    set @i=0
    select 
    @i=@i+1,@s=@s+','+cast(单价 as varchar)+' 单价'+cast(@i as varchar)+', sum (case when 单价='
    +cast(单价 as varchar)+ ' then 数量 end) 数量' + cast (@i as varchar)from tb group by  单价
    set @s='select 单位 '+@s+' from tb group by  单位'
    exec (@s)
    --删除测试
    drop table tb单位         单价1   数量1         单价2   数量2         
    ---------- ----- ----------- ----- ----------- 
    通大         1.25  100         1.50  400
    伟达         1.25  300         1.50  80