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
I have two tables A and BI want to compare the counts of policy number for agents.I am using the below query:
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
I am not getting the expected result.Can anyone help?
(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
I also want the data of the table 1 agents because their counts do not matched with table 2 expected results will be like these:
agent_pay policy_number 1011 1 1015 5 1016 6 1018 7
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
Not sure exactly what you are looking for here without knowing expected results
maybe this is what are you looking for :
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
I would use union all
and group 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;
This will include all agents that are in either table. You can add having sum(in_1) <> sum(in_2)
if you want the agents whose counts do not match.
You already have a chosen solution, but since you asked, here's how I see it:
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;
The result should look as shown below. Is this what you want?
id count_a count_b
---- ------- -------
1011 1 3
1012 1 1
1013 1 1
1014 1 1
1015 1 0
1018 1 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.