select 单位名,sum(现金) as 现金 from 表1 group by 单位名

解决方案 »

  1.   

    select 单位名,(select sum( 现金) as 现金 from 表1 where 表1.单位名 in (select 单位名 from 表2 t2 where t2.代码=t1.所属单位代码)) from 表2 t1
      

  2.   

    http://community.csdn.net/Expert/topic/3157/3157620.xml?temp=.9196588
      

  3.   

    select 表2.单位名,SUM(表3.现金) as 现金 FROM 表2 ,(select 表2.所属单位代码,sum(表1.现金) as 现金 from 表1,表2  group by 表2.所属单位代码) 表3 where 表2.所属单位代码 =表3.所属单位代码 group by 表2.单位名
      

  4.   

    一个极其愚蠢的方法,但好歹实现了:)
    select b.单位名, 
    case when b.代码 = b.所属单位代码 
    then (select sum(a.现金) from tab1 a, tab2 c where a.单位名 = c.单位名 and c.所属单位代码 = b.所属单位代码) 
    else (select sum(a.现金) from tab1 a where a.单位名 = b.单位名 group by a.单位名) end as 现金 
    from tab2 b
      

  5.   

    --查询
    select a.单位名,现金=sum(c.现金)
    from 表2 a
    left join 表2 b on a.代码=b.所属单位代码 and a.代码<>b.代码
    left join(
    select 单位名,现金=sum(现金) from 表1 group by 单位名
    )c on isnull(b.单位名,a.单位名)=c.单位名
    group by a.代码,a.单位名
    order by a.代码
      

  6.   

    --测试--测试数据
    create table 表1(单位名 varchar(10),现金 int)
    insert 表1 select '村1',100
    union  all select '村2',100
    union  all select '村1',50
    union  all select '村3',20create table 表2(单位名 varchar(10),代码 varchar(10),所属单位代码 varchar(10))
    insert 表2 select '乡镇1','001','001'
    union  all select '村1'  ,'002','001'
    union  all select '乡镇2','003','003'
    union  all select '村2'  ,'004','003'
    union  all select '村3'  ,'005','003'
    go--查询
    select a.单位名,现金=sum(c.现金)
    from 表2 a
    left join 表2 b on a.代码=b.所属单位代码 and a.代码<>b.代码
    left join(
    select 单位名,现金=sum(现金) from 表1 group by 单位名
    )c on isnull(b.单位名,a.单位名)=c.单位名
    group by a.代码,a.单位名
    order by a.代码
    go--删除测试
    drop table 表1,表2/*--测试结果单位名        现金          
    ---------- ----------- 
    乡镇1        150
    村1         150
    乡镇2        120
    村2         100
    村3         20(所影响的行数为 5 行)
    --*/
      

  7.   

    邹老大,能不能麻烦您讲一下,像我那样用case语句,效率会不会有比较大的损失啊~
    谢谢!
      

  8.   

    如果是Access,该如何实现呢?紧急求助!
      

  9.   

    在acess中用iif替换case:)select b.单位名, 
    iif(b.代码 = b.所属单位代码, (select sum(a.现金) from 表1 a, 表2 c where a.单位名 = c.单位名 and c.所属单位代码 = b.所属单位代码), 
    (select sum(a.现金) from 表1 a where a.单位名 = b.单位名 group by a.单位名)) as 现金 
    from 表2 b