USE master
GO


SELECT 
    'phcy' AS src
    ,dm1.Address_ID
    ,dm1.AD_first_name
    ,dm1.AD_last_name
    ,dm1.AD_middle_name
    ,dm1.AD_name
    ,dm1.AD_address_1
    ,dm1.AD_address_2
    ,dm1.AD_address_3
    ,dm1.AD_zip_code
    ,dm1.AD_city
    ,dm1.AD_sex

FROM Arizona.dbo.Address dm1
WHERE EXISTS(
  SELECT 1
  FROM Arizona.dbo.customer c
  WHERE c.CUST_add_turnover_to = dm1.address_id
    OR c.cust_address = dm1.address_id
    or c.cust_bill_to = dm1.address_id
    or c.cust_send_bill_to = dm1.address_id
    or c.cust_ship_to = dm1.address_id
)
AND dm1.AD_sex <> 4
AND dm1.Address_ID = 1500038158
;


SELECT 
    'ref' AS src
    ,dm1.Address_GUID
    ,dm1.AD_first_name
    ,dm1.AD_last_name
    ,dm1.AD_middle_name
    ,dm1.AD_name
    ,dm1.AD_address_1
    ,dm1.AD_address_2
    ,dm1.AD_address_3
    ,dm1.AD_zip_code
    ,dm1.AD_city
    ,dm1.AD_sex

FROM ArizonaRep.dbo.Address dm1
    JOIN ArizonaRep.[dbo].[Address_OU_link] l ON l.AOUL_address = dm1.Address_GUID
    JOIN ArizonaRep.[dbo].[Organizational_unit] ou ON ou.Organizational_unit_GUID = l.AOUL_OU
WHERE 1=1
--AND EXISTS(
--    SELECT 1
--    FROM ArizonaRep.[dbo].[Organizational_unit] ou
--        JOIN ArizonaRep.[dbo].[Address_OU_link] l ON l.AOUL_OU = ou.Organizational_unit_GUID
--    WHERE ou.OU_code='705'
--    AND l.AOUL_source_key = dm1.Address_GUID
--)
AND dm1.AD_sex <> 4
AND ou.OU_code='705'
AND l.AOUL_source_key = 1500038158
;

