计算记录的数量并将其插入临时表中

时间:2018-04-09 19:08:33

标签: sql sql-server

表A

agent_pay  status_ind  policy_number  company_code
---------  ----------  ------------- --------------
1011        B            001            06
1012        B            002            06
1013        B            003            06
1014        B            004            06
1015        B            005            06        
1016        B            006            06

表B

agent_pay   policy_number   service_ind
---------   -------------   ------------
1011          001                 X
1012          001                 S
1013          003                 X
1014          004                 S
1011          007                 X
1011         008                  S

有两个表。首先,我想检查两个表中针对代理的策略计数。如果表中的计数匹配,它将显示哪些策略与代理匹配。匹配的数据将去进入临时表。如果它没有匹配,它将进入错误表。我已经尝试了以下查询:

    (select a.agent_pay,count(policy_number) 
from table1 a group by a.agent_pay)
    intersect
    (select b.agent,count(policy_number) 
from table2 b where service_ind='x' group by b.agent)

请帮助我如何将数据插入SQL Server中的临时表?

1 个答案:

答案 0 :(得分:0)

- 请尝试此查询

create table tableA ( agent_pay int,  status_ind char(1), policy_number char(3),  company_code char(2))
go
insert into tableA 
VALUES (1011,'B',            '001',            '06'),
(1012,'B',            '002',            '06'),
(1013,'B',            '003',            '06'),
(1014,'B',            '004',            '06'),
(1015 ,'B',            '005',            '06'),        
(1016 ,'B',            '006',            '06')
go
create table tableB (agent_pay int, policy_number char(3), service_ind char(1))
INSERT INTO TABLEB
VALUES
(1011          ,'001',                 'X')
,(1012          ,'001',                 'S')
,(1013          ,'003',                 'X')
,(1014          ,'004',                 'S')
,(1011          ,'007',                 'X')
,(1011          ,'008',                  'S')
SELECT * FROM TABLEA
SELECT * FROM TABLEB
select a.agent_pay,count(policy_number) TableACount, sum(isnull(TableBCount,0))TableBCount
INTO #Temp
from tableA a 
LEFT JOIN
(select b.agent_pay ,count(policy_number) TableBCount
from tableB b where service_ind='x' 
group by b.agent_pay
)b on b.agent_pay = A.agent_pay
group by a.agent_pay
GO
SELECT * FROM #Temp t where t.TableACount = TableBCount
SELECT * FROM #Temp t where t.TableACount != TableBCount