教师表
FKID 工资 教师编号
4    12     009
4    5      009
6     3       099
6     13     099
2    55      004
1     55    003
规则表
ID   要求
4    40
6    10
1    10
2     30ID与FKID为外键关系
要求 
计算出一个教师(编号)的工资累计 如果超出规则表 则等于规则表要求字段值 否则正常

解决方案 »

  1.   

    不懂你的规则,一个教师编号009都包括了fkid 是4和6,怎么比较?
      

  2.   

    declare @a table(fkid int,工资 int,教师编号 int)
    insert @a 
    select 4,12,009
    union all
    select 4,5,009
    union all
    select 6,3,009
    union all
    select 6,13,009
    union all
    select 2,55,004
    union all
    select 1,55,003declare @b table(id int ,要求 int)
    insert @b 
    select 4,40
    union all
    select 6,10
    union all
    select 1,10
    union all
    select 2,30declare @c table(fkid int,num int)
    insert @c select fkid,sum(工资) as num from @a group by fkid
    select c.fkid,case when c.num>b.要求 then b.要求
                when c.num<b.要求 then c.num
         end
    from @b b,@c c 
    where c.fkid=b.id/*(所影响的行数为 6 行)
    (所影响的行数为 4 行)
    (所影响的行数为 4 行)fkid                    
    ----------- ----------- 
    4           17
    6           10
    1           10
    2           30(所影响的行数为 4 行)*/
      

  3.   

    单按fkid来比,可以:
    select a.fkid,case when a.工资>b.要求 then 要求 else 工资 end
    from 
    (select fkid,sum(工资) 工资 from [教师表] group by FKID) a
    Inner join 
    [规则表] b
    on a.fkid=b.id
      

  4.   

    修改:
    declare @a table(fkid int,工资 int,教师编号 int)
    insert @a 
    select 4,12,009
    union all
    select 4,5,009
    union all
    select 6,3,009
    union all
    select 6,13,009
    union all
    select 2,55,004
    union all
    select 1,55,003declare @b table(id int ,要求 int)
    insert @b 
    select 4,40
    union all
    select 6,10
    union all
    select 1,10
    union all
    select 2,30declare @c table(fkid int,num int)
    insert @c select fkid,sum(工资) as num from @a group by fkidselect 教师编号,sum(aa) 累计工资 from (
    select c.fkid,case when c.num>b.要求 then b.要求
                when c.num<b.要求 then c.num
         end aa
    from @b b,@c c 
    where c.fkid=b.id
    ) d,
    (
    select 教师编号,fkid from @a group by 教师编号,fkid) e
    where d.fkid=e.fkid
    group by 教师编号
    /*
    (所影响的行数为 6 行)
    (所影响的行数为 4 行)
    (所影响的行数为 4 行)教师编号        累计工资        
    ----------- ----------- 
    3           10
    4           30
    9           27(所影响的行数为 3 行)
    */