将求和值与主表进行比较

时间:2015-12-02 12:31:10

标签: sql sql-server-2008

表@ t1是主表,在导入后应该具有表@ t2的总和值。

DECLARE @t1 TABLE (
    typ         int,
    total       float
);

insert into @t1 (typ,total) values(1,30.0)
insert into @t1 (typ,total) values(2,70.0)
insert into @t1 (typ,total) values(3,99.9)

DECLARE @t2 TABLE  (
    typ     int,
    value   float
);

insert into @t2 (typ,value) values(1, 10.0)
insert into @t2 (typ,value) values(1, 20.0)
insert into @t2 (typ,value) values(2, 30.0)
insert into @t2 (typ,value) values(2, 40.0)
insert into @t2 (typ,value) values(3, 50.0)


select 
    t1.typ,
    t1.total, 
    t2.typ,
    t2.value,
    case when total = value then 'TRUE' else 'FALSE' end as Result
    from @t1 t1
left join @t2 t2 on t2.typ = t1.typ

结果:

typ|total|typ|value|Result
1  |30   |1  |10   |FALSE
1  |30   |1  |20   |FALSE
2  |70   |2  |30   |FALSE
2  |70   |2  |40   |FALSE
3  |99,9 |3  |50   |FALSE

当然,结果始终为“FALSE”,因为t2.value尚未汇总。

我的第一个想法是:

select 
    t1.typ,
    t1.total, 
    -- t2.typ,

    (select sum(t2.value) 
     from @t2 t2 
     where t1.typ = t2.typ
     group by typ) as Summed,

    case when total = (select sum(t2.value) 
                                         from @t2 t2 
                                         where t1.typ = t2.typ
                                         group by typ) then 'TRUE' else 'FALSE' end as Result
    from @t1 t1
  left join @t2 t2 on t2.typ = t1.typ

但我得到了这个

typ|total|Summed|Result
1  |30   |30    |TRUE
1  |30   |30    |TRUE
2  |70   |70    |TRUE
2  |70   |70    |TRUE
3  |99,9 |50    |FALSE

正确的结果必须如此:

typ|total|Summed|Result
1  |30   |30    |TRUE
2  |70   |70    |TRUE
3  |99,9 |50    |FALSE

我很乐意回答这个问题。

3 个答案:

答案 0 :(得分:1)

您可以使用OUTER APPLY

SELECT t1.typ, t1.total, x.Summed,
       CASE 
          WHEN x.Summed = t1.total THEN 'TRUE'
          ELSE 'FALSE'
       END          
FROM @t1 AS t1
OUTER APPLY (
   SELECT SUM(value) AS Summed
   FROM @t2 AS t2
   WHERE t1.typ = t2.typ ) AS x

答案 1 :(得分:1)

将case语句移动到派生表查询的外部查询:

select typ, total, 
    case when total = Summed then 'TRUE' else 'FALSE' end as Result 
from ( 
    select t1.typ,
        t1.total, 
        (select sum(t2.value) 
         from @t2 t2 
         where t1.typ = t2.typ
         group by typ) as Summed     
     from @t1 t1 
) t

答案 2 :(得分:0)

这通常是使用left join

完成的
select t1.typ, t1.total, t2.typ, t2.sumvalue,
       (case when t1.total = t2.sumvalue then 'TRUE' else 'FALSE' end) as Result
from @t1 t1 left join
     (select typ, sum(t2.value) as sumvalue
      from @t2 t2
      group by typ
     ) t2
     on t2.typ = t1.typ;

outer apply很好,但这使用标准SQL。