Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

T-SQL challenge

$
0
0

Hi,

I have table called addr_history and address. The address table stores recent data and addr_history stores the history of the address. In the below query I need minimum create_operator and minimum create_datetime combined with the address table for last update operator and last update datetime. Since addr_history has number of records against a person_id it is very difficult for me to filter the old records. Any thoughts??? 

SELECT * FROM
 (    
SELECT [pn_mship].[mship_id],
       [pn_membership].[person_id],
       [addr_history].[create_operator] as first_create_datetime,  --Added 
       [addr_history].[create_datetime] as first_create_datetime,  --Added
       [addr].[create_operator] as last_update_operator,
       [addr].[create_datetime] as last_update_datetime,
       [addr].[address_line1],
       [addr].[address_line2],
       [addr].[address_line3],
       [addr_type].[address_type],
       [addr].[locality],
       [addr].[state],
       [addr].[postcode],
       [addr].[barcode37],
       [pn_history].[deceased_flag],
       [address].dpid,
       ROW_NUMBER() over (PARTITION by [pn_mship].[mship_id],
                                       [pn_mship].person_id,
                                       [pn].[surname],
                                       [pen].[first_name]
                                       order by [pn_mship].[mship_id])rn     
  FROM [addr],
       [addr_history],
       [pn], 
       [addr_type],
       [pn_history],
       [pn_mship]
 where [pn_mship].[pn_id]=[pn].[person_id]
 AND   [pn].[person_id]=[addr].[person_id]
 AND   [pn_membership].[pn_id]=[pn_history].[person_id]
 AND   [pn_ship].termination_date is NULL
) t 
where rn=1
ORDER BY [create_datetime],[mship_id],[pn_id],[postcode]

Regards,

kccrga





Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>