比较两个表之间的列数

时间:2018-05-25 20:01:11

标签: sql sql-server

agent_pay   stautus_ind       policy_number 
1011           B                   1    
1012           B                   2    
1013           B                   3    
1014           B                   4    
1015           B                   5    
1018           B                   7    

agent   policy_number      service_ind
1011         1                  X
1012         1                  S
1013         3                  X
1014         4                  S
1011         7                  X
1011         8                  S

我有两个表A和B.我想比较代理商的政策编号。我使用以下查询:

select
    count(a.policy_number),
    a.agent_pay,
    count(b.policy_number),
    b.agent 
  from [AdventureWorksDW2012].dbo.[table1] a 
  inner join [AdventureWorksDW2012].dbo.[table2] b
    on a.agent_pay = b.agent
  group by a.agent_pay, b.agent

我没有得到预期的结果。任何人都可以帮忙吗?

(No column name)    agent_pay   (No column name)    agent
     1                1011            3             1011
     1                 1012           1             1012
     1                 1013           1             1013
     1                 1014          1              1014

我还想要表1代理的数据,因为它们的计数与表2不匹配 预期结果将如下:

agent_pay policy_number  1011 1  1015 5  1016 6  1018 7

4 个答案:

答案 0 :(得分:0)

select agent_pay, count(policynumber) cnt from (
Select agent_pay, policynumber from table1
union all
select agent, policynumber from table2)a
group by agent_pay

在不知道预期结果的情况下,不确定您在寻找什么

答案 1 :(得分:0)

也许这就是你在寻找什么:

SELECT  
    agent_pay, 
    policyCountA,
    COUNT(b.policy_number) AS policyCountB
FROM (
SELECT  
    a.agent_pay, 
    COUNT(a.policy_number) AS policyCountA
FROM [AdventureWorksDW2012].dbo.[table1] a
GROUP BY agent_pay 
 ) d
LEFT JOIN [AdventureWorksDW2012].dbo.[table2] b ON d.agent_pay = b.agent 
GROUP BY agent_pay, policyCountA

答案 2 :(得分:0)

我会使用union allgroup by

select agent, sum(in_1) as num_1, sum(in_2) as num_2
from ((select agent_pay as agent, 1 as in_1, 0 as in_2
       from table1
      ) union all
      (select agent as agent, 0 as in_1, 1 as in_2
       from table2
      )
     ) a
group by agent;

这将包括两个表中的所有代理。如果您希望代理的计数不匹配,可以添加having sum(in_1) <> sum(in_2)

答案 3 :(得分:0)

你已经有了一个选择的解决方案,但是既然你问过,我就是这样看的:

select
    coalesce(a.id, b.id) as id,
    coalesce(count_a, 0) as count_a,
    coalesce(count_b, 0) as count_b
  from (
    select agent_pay as id, count(*) as count_a from table1 
      group by agent_pay
  ) a
  full join (
    select agent as id, count(*) as count_b from table2 
      group by agent
  ) b on a.id = b.id;

结果应如下所示。这是你想要的吗?

  id  count_a  count_b
----  -------  -------
1011        1        3
1012        1        1
1013        1        1
1014        1        1
1015        1        0
1018        1        0