视图
a1  a2  a3
------------
1       400
1   01  200
1   02  100
2       300
2   01  300要求的结果
a1  a2  a3
-------------
1   01  0.5
1   02  0.25
2   01  1视图中..a1是标识项..a2是子项标志..比如视图中的01 02就表示不同的子项.但都属于a1中[1]这个大项下.空值的表示是这个大项总的值.子项的值是等于或者小于大项的总的值的..现在要求的结果表就是求子项的值占大项值的百分比...求解....

解决方案 »

  1.   

    use Tempdb
    go
    --> --> 
     
    if not object_id(N'Tempdb..#T') is null
    drop table #T
    Go
    Create table #T([a1] int,[a2] nvarchar(2),[a3] int)
    Insert #T
    select 1,null,400 union all
    select 1,N'01',200 union all
    select 1,N'02',100 union all
    select 2,null,300 union all
    select 2,N'01',300
    Go
    Select a.*,CAST(a.[a3]*1.0/b.a3 AS DECIMAL(5,2))
    from #T AS a
    INNER JOIN #T AS b ON a.[a1]=b.[a1] AND ISNULL(b.a2,'')=''
    WHERE ISNULL(a.a2,'')>''
    /*
    a1 a2 a3 (沒有資料行名稱)
    1 01 200 0.50
    1 02 100 0.25
    2 01 300 1.00
    */
      

  2.   

    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    create table [tb]([a1] int,[a2] varchar(3),[a3] int)
    insert [tb]
    select 1,'',400 union all
    select 1,'01',200 union all
    select 1,'02',100 union all
    select 2,'',300 union all
    select 2,'01',300select a1,a2, cast([a3]*1.0/(select [a3] from tb where a1=t.a1 and a2='') as decimal(8,2))from [tb] t where  a2!=''
    /*
    a1          a2   
    ----------- ---- ---------------------------------------
    1           01   0.50
    1           02   0.25
    2           01   1.00(3 行受影响)
    */
      

  3.   

    select
     a1,a2, cast(a3*1.0/(select a3 from tb where a1=t.a1 and a2='') as decimal(18,2))
    from
      tb t 
    where
      isnull(a2,'')<>''
      

  4.   

    drop table ta
    create table ta (a1 varchar(50),a2 varchar(50),a3 float)
    insert into ta values ('1','',400)
    insert into ta values  ('1','01',200)
    insert into ta values ('1','02',100)
    insert into ta values ('2','',300)
    insert into ta values  ('2','01',300)
    select * from taselect b.a1,a2,b.a3/a.a3 from ta b left join (select a1,max(a3)a3 from ta group by a1)a
    on b.a1=a.a1 where b.a3!=a.a3