数据库里有一张视图: V_对公存款 ,字段及数据为以下:(一个客户号对应一个客户名称)机构号   客户号     帐号    客户名称   月日均   1701     2006    23891   公司1     5000.00
1701     2006    23932   公司1     3000.00
1701     2007    28761   公司2     2300.00
1702     2007    28762   公司2     1198.00
....     ....    .....   ....      .......
现在我想实现的功能: 在 V_对公存款 做查询, 并 在字段"客户号" 下,把相同"客户号"的所有帐号的 "月日均 "相加起来,并在 V_对公存款
中新增一列,叫"月日均和",将"月日均和"添在每条记录后面.
实现后,效果如下:机构号   客户号     帐号    客户名称    月日均     月日均和1701     2006    23891   公司1     5000.00   8000.00
1701     2006    23932   公司1     3000.00   8000.00
1701     2007    28761   公司2     2300.00   3400.00
1702     2007    28762   公司2     1100.00   3400.00实现方法:可以在 V_对公存款 中新增一列, 或者 新建一个满足条件的视图. 因为我接下来还要将 V_对公存款(或新建视图) 与其他视图做 关联查询...
请教大家,谢谢!!!

解决方案 »

  1.   

    select *,月日均和=(select sum(月日均) from tb where 客户号=t.客户号)
    from tb t
      

  2.   

    --> 测试数据: #T
    if object_id('tempdb.dbo.#T') is not null drop table #T
    create table #T (机构号 int,客户号 int,帐号 int,客户名称 varchar(5),月日均 numeric(6,2))
    insert into #T
    select 1701,2006,23891,'公司1',5000.00 union all
    select 1701,2006,23932,'公司1',3000.00 union all
    select 1701,2007,28761,'公司2',2300.00 union all
    select 1702,2007,28762,'公司2',1198.00select *,月日均和=(select sum(月日均) from #T where 客户号=t.客户号)
    from #T t/*
    机构号         客户号         帐号          客户名称  月日均      月日均和                                     
    ----------- ----------- ----------- ----- -------- ---------------------------------------- 
    1701        2006        23891       公司1   5000.00  8000.00
    1701        2006        23932       公司1   3000.00  8000.00
    1701        2007        28761       公司2   2300.00  3498.00
    1702        2007        28762       公司2   1198.00  3498.00(所影响的行数为 4 行)*/
      

  3.   

    我接下来还要将 V_对公存款(或新建视图) 与其他视图(比如  V_对公_客户  )做 关联查询... 
    应该怎么做啊??????
    是这样吗??
    select a.月日均和
    (select *,月日均和=(select sum(月日均) from V_对公存款 where 客户号=a.客户号)
    from V_对公存款 a ) outer join V_对公_客户 where.........
      

  4.   

    select xxx,xxx
    from
    (
       select *,月日均和=(select sum(月日均) from V_对公存款 where 客户号=a.客户号) 
       from V_对公存款 a
    ) a
    outer join xxx
     on xx=xx
    where xx=xx
      

  5.   

    if object_id('tb','u') is not null
    drop table tb
    gocreate table tb (机构号 int,客户号 int,帐号 int,客户名称 varchar(5),月日均 numeric(6,2))
    insert into tb
    select 1701,2006,23891,'公司1',5000.00 union all
    select 1701,2006,23932,'公司1',3000.00 union all
    select 1701,2007,28761,'公司2',2300.00 union all
    select 1702,2007,28762,'公司2',1198.00
    go
    select a.*,s 日月均和 from tb a
    inner join
    (select 客户号,sum(月日均) s from tb group by 客户号) b
    on a.客户号=b.客户号
    go/*
    1701 2006 23891 公司1 5000.00 8000.00
    1701 2006 23932 公司1 3000.00 8000.00
    1701 2007 28761 公司2 2300.00 3498.00
    1702 2007 28762 公司2 1198.00 3498.00
    */