I have 2 tables with the following information. Unfortunately my basic knowledge of JOINS & MySQL isn't helping me achieve the result set I need... point 3 in particular is eluding me. Any help is greatly appreciated.
ORDERS
OrderID OrderDate Client Country
68349 1/1/2018 GSC Ltd US
93909 1/1/2018 XYZ Ltd UK
39900 3/31/2018 ABC Ltd US
69382 4/4/2018 ABC Ltd US
94500 6/21/2018 DEF Ltd US
93911 1/1/2018 TUV Ltd UK
REPORTS
RepID State RepDate Building OrderID
1 AK 1/1/2018 PE James 93909
2 CA 4/2/2018 PE Grid 93909
3 CA 3/31/2018 PMU Jaya 39900
4 WA 4/4/2018 PMU Taman 69382
5 CA 6/21/2018 PE Grid 94500
6 CA 3/31/2018 PMU Wate 39900
I need to select all based on :
- Select orders where the Country is = US
- Select reports that were a part of those US Orders (ie Order ID = Order ID from result above)
- Most importantly: Filter the result of the reports so that it only shows the single latest Report (based on most Recent RepDate) for each Building
So the results would be:
OrderID OrderDate Client Country RepID RepDate Building
68349 1/1/2018 GSC Ltd US - - -
39900 3/31/2018 ABC Ltd US 3 3/31/2018 PMU Jaya
69382 4/4/2018 ABC Ltd US 4 4/4/2018 PMU Taman
94500 6/21/2018 DEF Ltd US 5 6/21/2018 PE Grid
The result below would be excluded since there is a more recent report for "PE Grid":
OrderID OrderDate Client Country RepID RepDate Building
39900 3/31/2018 ABC Ltd US 6 3/31/2018 PE Grid