--SELECT * FROM dbo.custport_klaim WHERE core_no_klaim = '2016.272839'
--SELECT * FROM dbo.custport_from_aai_header_history WHERE claim_register = 'C1610000063'

INSERT INTO [GrpInsurance].[dbo].[custport_klaim_link]
           ([id_klaim]
           ,[claim_id]
           ,[no_klaim])
SELECT
  ck.id_klaim,
  --ck.no_klaim,
  aai.claim_id,
  ck.core_no_klaim
FROM
  dbo.custport_klaim AS ck INNER JOIN
  (
    SELECT DISTINCT
    	claim_register,
    	claim_id
    FROM
    	dbo.custport_from_aai_header
    WHERE
      claims_process_status IN ('13','14')
  ) AS aai ON ck.no_klaim = aai.claim_register
WHERE
--  ck.core_no_klaim IS NOT NULL
  ck.id_klaim NOT IN (SELECT id_klaim FROM dbo.custport_klaim_link)
ORDER BY
  ck.id_klaim

--SELECT * FROM dbo.custport_klaim_history WHERE id_klaim=487
--SELECT * FROM dbo.custport_from_aai_header_history WHERE claim_id = '109550'