从多列过滤空值

时间:2012-06-12 18:54:15

标签: sql sql-server sql-server-2005

使用SQL Server 2005。

数据位于2个单独的表中,我只获得了写权限。

数据如下:

DateTime1  |  DateTime2
-----------------------
2012-06-01 | 2012-06-01
2012-06-02 | 2012-06-02
2012-06-04 | 2012-06-05
2012-06-02 | NULL
NULL       | 2012-06-05
2012-06-04 | 2012-06-05
NULL       | NULL

我想要做的是能够计算DateTime1和DateTime2包含值的值,DateTime1包含日期,DateTime2为NULL,DateTime1为NULL,DateTime2包含值。

总的来说,我试图避免DateTime1为空,而DateTime2为空。

我的 其中 语句如下所示:

Where (DateTime1 is not null or DateTime2 is not null)

唯一的问题是它仍然显示两者都是空值。任何人都知道为什么会这样或者如何解决它?

由于

修改 @Lamak要求的完整查询

;With [CTE] As (
Select
    TH.ID
    ,AMT
    ,Reason
    ,EffDate
    ,DateReq
    ,CS_ID
    ,ROW_NUMBER()
        Over (Partition By ID Order By [pthPrimeKey] Desc) as [RN]
From
    DateTime1Table as [MC] (nolock)
    Left Join History as [TH] (nolock) on [TH].[ID] = [MC].[ID]
    Left Join Trans as [SUB] (nolock) on [SUB].TransactionReasonCode = [TH].Reason
    Left Join Renew as [RM] (nolock) on [MC].ID = [RM].ID
Where 
    ([MC].[DateTime1] is not null or [RM].[DateTime2] is not null)
    And [PostingDate] = DATEADD(dd, datediff(dd, 1, GetDate()),0)
)
SELECT 
[ID]
,[AMT] as [Earned]
,[Reason] as [Reason]
,[EffDate] as [Eff]
,[DateReq] as [Date_Cancel_Req]
,[pthUserId_Number] as [CSR]
FROM [CTE]
Where RN <= 1

1 个答案:

答案 0 :(得分:5)

如果

,则允许包含行
  • 仅DateTime1具有值
  • 仅DateTime2具有值
  • 都有值

它将排除两个值均为NULL的行。这就是你要追求的吗? (我试着跟着对话但迷路了,并希望你有一个更简单的repro与样本数据 - 我认为CTE和所有其他连接和逻辑真正消除了你所遇到的实际问题。)

WHERE COALESCE([MC].[DateTime1], [RM].[DateTime2]) IS NOT NULL

但是,由于您正在执行LEFT OUTER JOIN,因此这可能属于ON的{​​{1}}条款,而不是[RM]。否则,您将不知道是否排除了行,因为匹配行中的值为NULL,或者因为没有匹配的行。也许那没关系,只是想我会提到它。

修改

当然,该条款提供与......完全相同的结果。

WHERE

想要证明吗?

WHERE ([MC].[DateTime1] is not null or [RM].[DateTime2] is not null)

两个查询都会产生:

DECLARE @a TABLE(id INT, DateTime1 DATETIME);
DECLARE @b TABLE(id INT, DateTime2 DATETIME);

INSERT @a SELECT 1, '20120602' ; INSERT @b SELECT 1, NULL;
INSERT @a SELECT 2, NULL       ; INSERT @b SELECT 2, '20120605';
INSERT @a SELECT 3, '20120604' ; INSERT @b SELECT 3, '20120605';
INSERT @a SELECT 4, NULL       ; INSERT @b SELECT 4, NULL;
INSERT @a SELECT 5, '20120602' ; INSERT @b SELECT 9, NULL;
INSERT @a SELECT 6, NULL       ; INSERT @b SELECT 10, '20120605';
INSERT @a SELECT 7, '20120604' ; INSERT @b SELECT 11, '20120605';
INSERT @a SELECT 8, NULL       ; INSERT @b SELECT 12, NULL;

SELECT * FROM @a AS a LEFT OUTER JOIN @b AS b
ON a.id = b.id
WHERE COALESCE(a.DateTime1, b.DateTime2) IS NOT NULL;

SELECT * FROM @a AS a LEFT OUTER JOIN @b AS b
ON a.id = b.id
WHERE a.DateTime1 IS NOT NULL OR b.DateTime2 IS NOT NULL;

正如我在评论中建议的那样,如果您没有看到预期的行,则需要查看查询的其他部分。如果您提供样本数据和所需结果,我们可以尝试帮助您缩小范围。事实上,我认为我们对您的架构和数据知之甚少,无法确定问题所在。