表:table(入库表)有字段:a1,a2,a3
记录有:
编码    金额    厂商
01223   23      aa
02223   23      cc
03223   22      aa
01224   24      ee
03224   23      nn
编码01表示中草药, 02表示西药请用一条SQL语句统计每个厂商入库的西药金额,中草药金额一条SQL语句我只能统计出西药的
select sum(a2) as a2, a3 from tablegroup by a3 where left(a1,2)='02'

解决方案 »

  1.   

    select a3, left(a1,2) as a1, sum(a2) as a2
    from table
    group by a3 , left(a1,2)
      

  2.   

    create table table1 
    (编码 char(10),   金额 int,   厂商 varchar(10))
    insert table1
    select '01223'  , 23     , 'aa'
    union all select 
    '02223',   23,      'cc'
    union all select 
    '03223',   22,      'aa'
    union all select 
    '01224',   24,      'ee'
    union all select 
    '03224',   23,      'nn'select 厂商,编码,sum(金额) [金额] from table1 group by 编码,厂商,left(编码,2)
    --order by 编码
    drop table table1
    厂商         编码         金额          
    ---------- ---------- ----------- 
    aa         01223      23
    ee         01224      24
    cc         02223      23
    aa         03223      22
    nn         03224      23
      

  3.   

    二楼的就可以了,你那句话语法都有错!-- group by a3 where left(a1,2)='02'  不能这样写的!
      

  4.   

    不知道是我表达的不好还是怎么回事.
    编码    金额    厂商
    01223   23      aa
    02223   23      cc
    03223   22      aa
    01224   24      ee
    03224   23      nn
    01224   23      aa
     
    我的意思是找出来记录是
    厂商  中草金额  西药金额
    aa    46        22
    cc              23
    ee    24
      

  5.   

    应该是你表达的不好,你开始写道:编码01表示中草药, 02表示西药
    但你上面的数据 03223   22      aa  却被你算到西药价格中,我下面按照01和02的标准给你写。
    create table table1 
    (编码 char(10),   金额 int,   厂商 varchar(10))
    insert table1
    select '01223'  , 23     , 'aa'
    union all select 
    '02223',   23,      'cc'
    union all select 
    '03223',   22,      'aa'
    union all select 
    '01224',   24,      'ee'
    union all select 
    '03224',   23,      'nn'
    union all select 
    '01224',   23 ,     'aa'
    union all select '02211',10,'aa'select 厂商,sum(中药价格) [中药价格],sum(西药价格) [西药价格] from 
    (
    select 厂商,中药价格=sum(case left(编码,2) when '01' then 金额 else 0 end) 
    ,西药价格=sum(case left(编码,2) when '02' then 金额 else 0 end) from table1 group by 厂商,left(编码,2)
    --order by 编码
    )ta
    group by 厂商
    drop table table1---结果
    厂商         中药价格        西药价格        
    ---------- ----------- ----------- 
    aa         46          10
    cc         0           23
    ee         24          0
    nn         0           0
      

  6.   

    呵呵..借用上面的..如果你不想显示nn的话..加个where就行了.select 厂商,sum(中药价格) [中药价格],sum(西药价格) [西药价格] from 
    (
    select 厂商,中药价格=sum(case left(编码,2) when '01' then 金额 else 0 end) 
    ,西药价格=sum(case left(编码,2) when '02' then 金额 else 0 end) from table1 
    where left(编码,2) in ('01','02')
    group by 厂商,left(编码,2)
    --order by 编码
    )ta
    group by 厂商