如何获得没有NULL的最新日期?

时间:2012-11-08 22:24:51

标签: sql sql-server-2005 datetime

我正在尝试根据他们的派遣日期从工作中提取工单,以找到被忽视的工作。我只希望工作订单具有该作业的最新发货日期,以便我可以确定自上次发送到指令的时间。但是,我不想拉任何具有空工作订单的作业,因为这些工作正在被调度。我尝试了一个ROW_NUMBER语句,然后只拉了顶行,但我需要空值首先显示在列表上然后显示最新日期,这样就不起作用了。这些作业也有一个打开或关闭的状态,而打开的作业总是空的。这是我到目前为止的脚本:

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]

这就是我得到的:

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

这就是我需要的,除了这些机会实际上有等待分派的空日期的开放工单。

1 个答案:

答案 0 :(得分:1)

在where子句中添加NOT EXISTS项检查:

...

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]