This is my first question on here so please be gentle. I have a master and details table that represent a trip/excursion (mainrequest) and the itinerary of said excursion. The itinerary contains 0 to many items that have a start date and an end date. I need to display report on each trip showing data from the mainrequest along the min start date for that request and max end for the same request. The key is the requestID. I have this so far but I cannot find a way to express the end date in the same context:
select MainRequest.RequestID, UKINT, ReasonForTrip, TripNumber, Itinerary.[Start Date]
from MainRequest
right join
(Select RequestID, Min(StartDate) As [Start Date]
from Itinerary
group by RequestID) Itinerary
ON (MainRequest.RequestID = Itinerary.RequestID)
Sorry if I've posted incorrectly. Thanks
You would normally LEFT JOIN from the "main table" to table with optional data, like @jarlh says
try this
SELECT MainRequest.RequestID, UKINT, ReasonForTrip
,TripNumber, Itinerary.[Start Date], Itinerary.[End Date]
FROM MainRequest
LEFT JOIN
(
SELECT RequestID, Min(StartDate) As [Start Date]
,MAX(EndDate) As [End Date]
FROM Itinerary
GROUP by RequestID
) Itinerary
ON (MainRequest.RequestID = Itinerary.RequestID)
SELECT
DISTINCT
m.RequestID,
m.UKINT,
m.ReasonForTrip,
m.TripNumber,
min(i.StartDate) over (partition by m.RequestID) [Start Date],
max(i.EndDate) over (partition by m.RequestID) [End Date]
FROM
MainRequest m
LEFT JOIN
Itinerary i
ON
m.RequestID = i.RequestID
Thanks for all your help guys, I'm not sure about the left right join thing, I went W3C schools and the venn for the right join seemed to make more sense than the left join. The right join in this instance returns correct data but I am always keen to learn so if any of you would like to elaborate on an Elmo level I'm all ears!!! Thanks to Cool_Br33ze for the pointer and jarlh for editing my question. I think I've sussed the indent thing now!! The answer is what we went with but Cool_Br33ze was the inspiration for it.
Select
MainRequest.RequestID,
UKINT,
ReasonForTrip,
TripNumber,
Itinerary.[Start Date],
Itinerary.[End Date]
from
MainRequest
right join
(Select
RequestID,
Min(StartDate) As [Start Date],
Max(EndDate) As [End Date]
from
Itinerary group by RequestID)
Itinerary
ON (MainRequest.RequestID = Itinerary.RequestID)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.