I'm writing my first SQL query, so please excuse my lack of knowledge on the matter.
I'm looking to filter multiple times from each join, and it seems the executed query total rows is growing, instead of shrinking.
/*
Reads Order Status, determines if it's OPEN
Pulls all OPEN orders to Time Tickets
Reads the Time Ticket TicketDate, determines if it's > 90 days old
Compares PODet JobNo, joins PO table
Reads the PO DateMod, determines if it's > 90 days old
*/
DECLARE @now DATETIME
DECLARE @90daysago DATETIME
SET @now = GETDATE()
SET @90daysago = DATEADD(day, -90, @now)
SELECT
o.JobNo,
o.OrderNo,
o.PartNo,
o.Status,
o.JobNo,
t.TicketDate,
p.Status,
p.OutSideService,
p.PONum,
po.DateEnt,
po.DateMod
FROM
RBCBEMD.dbo.OrderDet AS o /* OrderDet = o */
INNER JOIN RBCBEMD.dbo.TimeTicketDet AS t /* TimeTicket = t */
ON o.JobNo = t.JobNo
INNER JOIN RBCBEMD.dbo.PODet AS p /* PODet = p */
ON o.JobNo = p.JobNo
INNER JOIN RBCBEMD.dbo.PO AS po /* PO = po */
ON p.PONum = po.PONum
WHERE
o.Status = 'Open' AND
t.TicketDate <= @90daysago AND
po.DateMod <= @90daysago
ORDER BY
cast(t.TicketDate as DATETIME) DESC
The query is supposed to go find the OPEN orders from the OrderDet table. From there, if it is OPEN then pull in the last TicketDate from the TimeTicketDet table. Determine if the TicketDate is >90 days old. If it is >90 days old, pull the PONum from the PO table, find its DateMod and determine if it is >90 days old.
If the (o.status ='Open') AND (t.ticketDate >90 days old) AND (po.DateMod >90 days old) then post the result for the JobNo.