Reputation: 71
I am having some serious problems wrapping my head around how to build a proper query for my situation.. Pretty sure it depends on joining the tables properly but I cant seem to figure it out after a lot of googling...
I have the following tables..
Main:
ID, WhenDate, InfoText, StatusID, TypeID
and...
Status:
ID, StatusText
and...
Secondary:
MainID, WhenDate
Hope Im able to explain this correctly..
I have a bunch of records in Main that I need to get info from.. I need to be able to filter on WhenDate and TypeID. I also need to get StatusText from Status table that is linked to StatusID.
The problem:
The table Secondary links to records in Main, any record in Secondary should result in a row that is identical to the record in Main with the exception that the WhenDate in Secondary is used instead of the WhenDate in Main.
Any help greatly appreciated, even if its just a hint, such as what types of joins to use or something...
Upvotes: 2
Views: 1225
Reputation: 116100
I used INNER JOIN
for status, assuming that every main record refers to an existing status record. If that is not the case, you may want to change it to a LEFT JOIN
.
For the WhenDate, you can just left join Secondary. If a record is found, you can compare against Secondary.WhenDate, otherwise, check against Main.WhenDate.
SELECT
m.ID as MainID,
m.WhenDate as MainWhenDate,
m.InfoText,
m.StatusID,
st.StatusText,
m.TypeID,
s.WhenDate as SecondaryWhenDate,
CASE WHEN s.MainID IS NULL THEN
m.WhenDate
ELSE
s.WhenDate
END AS ActualWhenDate
FROM
Main m
INNER JOIN Status st ON st.ID = m.StatusID
LEFT JOIN Secondary s ON s.MainID = m.ID
WHERE
( s.MainID IS NULL AND m.WhenDate = <YourDate>
OR
s.MainID IS NOT NULL AND s.WhenDate = <YourDate> )
AND TypeId = <TypeFilter>
AND ... other filters, if you need any ...
Upvotes: 1