select a.营业员,b.类型,数量=count(*),金额=sum(a.商品单价)
from 表1 a
join 表2 b on a.商品代码=b.商品代码

解决方案 »

  1.   

    select 营业员,count(商品代码),剂型
    from 表1,表2
    where 表1商品代码 =表2.商品代码 
    group by 营业员,剂型
      

  2.   

    我水平差
    只知道用游标来做
    期望一个SQL解决的答案
      

  3.   

    --查询
    declare @s varchar(8000)
    set @s=''
    select @s=@s+',['+类型+']=sum(case 商品代码 when '''+cast(商品代码 as varchar)+''' then 商品单价 else 0 end)'
    from 表2
    group by 商品代码,类型
    exec('select 营业员'+@s+'
    from 表1
    group by 营业员')
      

  4.   

    --测试--测试数据
    create table 表1(营业员 int,商品代码 int,商品单价 int)
    insert 表1 select 1,1,34
    union  all select 3,2,45
    union  all select 2,3,2
    union  all select 3,3,30create table 表2(商品代码 int,类型 varchar(10))
    insert 表2 select 1,'片剂'
    union  all select 2,'针剂'
    union  all select 3,'水剂'
    go--查询
    declare @s varchar(8000)
    set @s=''
    select @s=@s+',['+类型+']=sum(case 商品代码 when '''+cast(商品代码 as varchar)+''' then 商品单价 else 0 end)'
    from 表2
    group by 商品代码,类型
    exec('select 营业员'+@s+'
    from 表1
    group by 营业员')
    go--删除测试
    drop table 表1,表2/*--测试结果营业员         片剂          针剂          水剂          
    ----------- ----------- ----------- ----------- 
    1           34          0           0
    2           0           0           2
    3           0           45          30--*/
      

  5.   

    declare @s varchar(8000)
    set @s=''
    select @s=@s+',['+b.类型+']'+case when a.商品代码 is null then '=0'
    else '=sum(case 商品代码 when '''+cast(a.商品代码 as varchar)+''' then 商品单价 else 0 end)' end
    from 表2 a 
    right join 表3 b on a.类型=b.类型
    group by a.商品代码,b.类型
    exec('select 营业员'+@s+'
    from 表1
    group by 营业员')
      

  6.   

    select c.营业员,c.类型,(select count(*) from 表1,表2 where 表1.商品代码=表2.商品代码 and 表2.类型=c.类型 and c.营业员=表1.营业员 ) 数量 from (select * from (select distinct 营业员  from 表1) a,(select distinct 类型  from 表2) b) c order by c.营业员,c.类型