我在数据库中有四个表:
CustomerMaster
, Addresses
, EmailAddresses
, &PhoneNumbers
Addresses
, EmailAddresses
, & PhoneNumbers
referenceCustomerMaster
的主键。
我想创建一个查询来获取每个客户的最新客户信息CustomerMaster
。我知道如何将表连接在一起,但我不知道如何利用这些字段仅从、和中的每个客户的表中TimeStamp
检索最新更新的数据。Addresses
EmailAddresses
PhoneNumbers
CustomerMaster
SQL小提琴: Working Example
客户大师:
| CUS_PK | CUS_FirstName | CUS_LastName | CUS_AccountNum
| 1 | mickey | mouse | 000001
| 2 | donald | duck | 100000
地址:
| ADD_CUS_FK | ADD_StreetAddress | ADD_City | ADD_StateProvince | ADD_PostalCode | ADD_TimeStamp
| 1 | Disney World | Orlando | Florida | 99999 | 2000-01-01 12:00:00.000
| 1 | Disney Land | Anaheim | California | 12345 | 2012-12-23 12:00:00.000
| 2 | Disney World | Orlando | Florida | 99999 | 2001-01-01 12:00:00.000
电子邮件地址:
| EMA_CUS_FK | EMA_EmailAddress | EMA_TimeStamp
| 1 | supermouse@disney.com | 2005-01-01 12:00:00.000
| 1 | mousehouse@disney.com | 2006-01-01 12:00:00.000
| 2 | scrougeheir@disney.com | 2001-01-01 12:00:00.000
电话号码:
| PHO_CUS_FK | PHO_PhoneNumber | PHO_TimeStamp
| 1 | 999-999-9999 | 2001-01-01 12:00:00.000
| 1 | 012-345-6789 | 2013-01-01 12:00:00.000
| 2 | 666-867-5309 | 2001-01-01 12:00:00.000
询问:
SELECT DISTINCT cm.CUS_FirstName, cm.CUS_LastName, cm.CUS_AccountNum,
addr.ADD_StreetAddress, addr.ADD_City,
addr.ADD_StateProvince, addr.ADD_PostalCode,
email.EMA_EmailAddress, phone.PHO_PhoneNumber
FROM CustomerMaster AS cm
JOIN Addresses AS addr
ON cm.CUS_PK = addr.ADD_CUS_FK
JOIN EmailAddresses AS email
ON cm.CUS_PK = email.EMA_CUS_FK
JOIN PhoneNumbers AS phone
ON cm.CUS_PK = phone.PHO_CUS_FK
ORDER BY cm.CUS_AccountNum
当前结果:
Mickey | Mouse | 000001 | Disney World | Orlando | Florida | 99999 | supermouse@disney.com | 999-999-9999
Mickey | Mouse | 000001 | Disney World | Orlando | Florida | 99999 | supermouse@disney.com | 012-345-6789
Mickey | Mouse | 000001 | Disney World | Orlando | Florida | 99999 | mousehouse@disney.com | 999-999-9999
Mickey | Mouse | 000001 | Disney World | Orlando | Florida | 99999 | mousehouse@disney.com | 012-345-6789
Mickey | Mouse | 000001 | Disney Land | Anaheim | California | 12345 | supermouse@disney.com | 999-999-9999
Mickey | Mouse | 000001 | Disney Land | Anaheim | California | 12345 | supermouse@disney.com | 012-345-6789
Mickey | Mouse | 000001 | Disney Land | Anaheim | California | 12345 | mousehouse@disney.com | 999-999-9999
Mickey | Mouse | 000001 | Disney Land | Anaheim | California | 12345 | mousehouse@disney.com | 012-345-6789
Donald | Duck | 100000 | Disney World | Orlando | Florida | 99999 | scrougeheir@disney.com | 666-867-5309
期望的结果:
Mickey | Mouse | 000001 | Disney Land | Anaheim | California | 12345 | mousehouse@disney.com | 012-345-6789
Donald | Duck | 100000 | Disney World | Orlando | Florida | 99999 | scrougeheir@disney.com | 666-867-5309
我需要如何编辑现有查询以获得所需的结果集?
请提供增强的 SQL 查询(最好是 SQL Fiddle)