如何将count()与另一个表中的值进行比较?

时间:2015-03-13 13:58:40

标签: sql-server

我有2张桌子。我想将表a中的行数与表b中的值进行比较:

select count(1)  from table_a; -- returns 1500
select row_count from table_b; -- returns 1490

我想比较数字并执行并相应地在表c中写一行。我想过做一个连接,但这没有意义,因为a和b的值是不相关的:

select
      count(a.*) as rows_in_table
    , b.lines_in_loadfile
from
    [table_a] a
    cross join [table_b]    
;

现在我很困惑。在伪我需要的是:

select
    count(1) from table_a as value_a
    row_count from table_b as value_b

case
    when value_a <> value_b then msg = 'values do not match'
    else msg = 'values match'
end

insert into table_c (row_msg) = @msg;

如何在1个查询中完成此操作?我很确定这不是那么难,但现在已经盯着它看了一个小时而且卡住了。

3 个答案:

答案 0 :(得分:1)

insert into table_c (row_msg)
select
    CASE
       WHEN 
          (selectcount(1) from table_a ) != 
          (select row_count from table_b) THEN 'values do not match'
       ELSE 'values match' 
    END

我不确定&#34;从table_b&#34;中选择row_count部分。你如何确保它只返回一个值?

答案 1 :(得分:1)

假设每个表中只有一行:

SELECT a.value_a, b.value_b
     , msg  = case
       when value_a = b.value_b then 'values do match'
       else 'values do not match'
       end
FROM
( select count(*)  value_a from table_a) a ,
( select row_count value_b from table_b) b

答案 2 :(得分:0)

这是方式:

INSERT INTO TABLE_C
    (row_msg)

    SELECT
          CASE
        WHEN COUNT(a.*) <> b.lines_in_loadfile THEN 'Values do not match'
        ELSE 'Values match'
    END
    FROM
        [table_a] a
        cross join [table_b]