I've been trying to figure out how to join a table to other tables that I've joined but the way the tables are set-up, EventTable has the OrderID only if certain events happen. Otherwise it's Null.
EventTable
EventID EventName OrderID DateTS
1 Rec 1 date1
2 Track NULL date2
3 Run NULL date3
EventItemTable
EventID Column2 OrderID
1 Other 1
2 stuff 2
3 beer 3
OrderTable
OrderID orderRef ProdID
1 1234 1
2 1233 1
3 1232 3
Now I've been trying to get all the Event rows which has all of the events that I'm looking for. What I need to be able to do is be able to allow users to use Tableau which will filter the orderRef column to show all the events that occurred.
I'm pretty new to SQL queries and the per row logic I'm thinking would be if statement but don't know how it would work in SQL.
SELECT OrderTable.orderRef, EventTable.DateTS, EventTable.EventName
If EventTable.OrderID column isNull, then
FROM EventItemTable
join EventItemTable ON EventItemTable.OrderID = EventTable.OrderID
join OrderTable ON OrderTable.OrderID = EventItemTable.OrderID
ELSE
FROM EventItemTable
left join OrderTable ON OrderTable.OrderID = EventTable.OrderID
In my mind, I would think that the orderRef would then be populated in the entire table and have no nulls or be filter out. I would still be able to have all the other columns but with the else condition the rows would just be populated with NULL. I've been looking at subqueries and other functions to try but not seeing anything that seems to be able to do this. I'm using a Microsoft SQL 2005 (I believe)
EDIT
This is what I ended up with that got all the OrderID in one column to join with @AlexJohnson suggestion. My issue now is that a couple have duplicate manufacturingEventID in the rows per order reference. Not sure if the ISNULL is causing that issue
SELECT met.met_ManufacturingEventID
,met.met_OrderID
,ori.ori_OrderID
,mfi.mfi_OrderID
,mfi.mfi_LastEvent
,mfi.mfi_RunNumber
,mfi.mfi_InputOrder
,meo.meo_ManufacturingOperationName
,mes.mes_ManufacturingStationName as StationName
,mes.mes_StationStatusName as StationStatus
,met.met_EventDate as EventDate
-- ,oie.oie_EventDate
,met.met_ToothID
,met.met_Comment as metComment
,met.met_ManufacturingOrderNumber
-- ,ISNULL(mfi.mfi_OrderID,met.met_OrderID) as OrderID
,ord.ord_OrderReference as OrderRef
FROM [dbo].[ManufacturingEvents] met
LEFT JOIN [dbo].[ManufacturingEventOrderItems] mfi
ON mfi.mfi_ManufacturingEventID = met.met_ManufacturingEventID
LEFT JOIN [dbo].[OrderItems] ori
ON ori.ori_OrderItemID = mfi.mfi_OrderItemID
LEFT JOIN [AtlantisProductionSystem_Prod_US].[dbo].[Orders] ord
ON ord.ord_OrderID = ISNULL(mfi.mfi_OrderID,met.met_OrderID)
LEFT JOIN dbo.ManufacturingStations mes
ON mes.mes_ManufacturingStationID = met.met_ManufacturingStationID
JOIN dbo.ManufacturingOperations meo
ON meo.meo_ManufacturingOperationID = mes.mes_ManufacturingOperationID