Gup3rSuR4c
Gup3rSuR4c

Reputation: 9490

How can I get the most recent date that doesn't have a NULL?

I am trying to pull work orders from jobs based on their dispatch date to find neglected jobs. I only want the work order with the most recent dispatch date for that job so I can determine how long since it was last dispatched to. However, I do not want to pull any jobs that have null work orders because these are in the process of being dispatched. I tried a ROW_NUMBER statement and then only pulling the top row, but I would need nulls to show up first on the list then the latest date so that didn't work. The jobs also have a status with them open or closed and the open ones are the ones that are always null Here is the script I have so far:

SELECT DISTINCT

    [O].[Name] AS [Opportunity],
    [O].[Office_Location__c] AS [Office],
    MAX([WO].[saasdisp__Dispatch_Date__c]) AS [MaxDate]

FROM    [Opportunity] AS [O]
    JOIN [saasdisp__Work_Order__c] AS [WO] ON ([O].[Name] = [WO].[OppName__c]
                AND [O].[Id] = [WO].[Opportunity__c])

WHERE   [O].[StageName] = 'In Progress'


GROUP BY    [O].[Name],
            [O].[Office_Location__c]

This is what I'm getting:

Opportunity         Office        MaxDate
Azad, Fariba          LA    2012-11-08 00:00:00.000
Cantrell, Timothy L.  LA    2012-11-07 00:00:00.000
Feiner, Jeffrey       LA    2012-11-06 00:00:00.000
Greasby, Kat          LA    2012-11-06 00:00:00.000

Which is what I need, except that these opportunities actually have open work orders with null dates waiting to be dispatched.

Upvotes: 1

Views: 87

Answers (1)

Michael Fredrickson
Michael Fredrickson

Reputation: 37388

Add a NOT EXISTS check to your where clause:

...

WHERE   [O].[StageName] = 'In Progress'

AND NOT EXISTS (
    SELECT *
    FROM [saasdisp__Work_Order__c] AS [WO2] 
    WHERE [WO2].[saasdisp__Dispatch_Date__c] IS NULL
          AND [O].[Name] = [WO2].[OppName__c]
          AND [O].[Id] = [WO2].[Opportunity__c]
)


GROUP BY    [O].[Name],
            [O].[Office_Location__c]

Upvotes: 1

Related Questions