如何处理where子句'9999-01-01 00:00:00.000'中的默认值

时间:2016-07-28 04:10:11

标签: sql sql-server

SELECT 
    u.FirstName, MiddleName, u.LastName, u.Address,
    u.Address2, u.City, u.State UserState, 
    u.PostalCode, u.Country, DateOfBirth
FROM 
    Users u
INNER JOIN 
    Companies c ON c.CompanyID = u.CompanyID
WHERE
    -- Users active/logged in within last 365 days
    u.ActiveEnd BETWEEN DATEADD(MM, DATEDIFF(MM, 0, getdate()) - 12, 0)
                    AND DATEADD(DD, -1, DATEADD(MM, DATEDIFF(MM, 0, getdate()), 0))  
    --all Active Companies or Companies deactivated within the last 60 days
    OR c.ActiveEnd BETWEEN DATEADD(MM, DATEDIFF(MM, 0, getdate()) - 2, 0) 
                       AND DATEADD(DD, -1, DATEADD(MM, DATEDIFF(MM, 0, getdate()), 0))

此处默认情况下,'ACTIVEEND'列值在UsersCompanies表的整个表格中为'9999-01-01 00:00:00.000'。

我不知道如何在上面的where子句中编写处理/管理此默认值的条件。

1 个答案:

答案 0 :(得分:0)

假设您要排除这些默认日期,您可以执行以下操作:

SELECT 
    u.FirstName, MiddleName,u.LastName,u.Address,
    u.Address2, u.City,u.State UserState,u.PostalCode,u.Country,DateOfBirth
FROM 
    Users u
    INNER JOIN Companies c ON c.CompanyID = u.CompanyID
WHERE
    -- date is not default
    u.ActiveEnd != '9999-01-01 00:00:00.000' AND
    (
        -- Users active/logged in within last 365 days
        u.ActiveEnd BETWEEN  DATEADD(MM, DATEDIFF(MM,0,getdate())-12, 0) AND DATEADD(DD,-1,DATEADD(MM, DATEDIFF(MM,0,getdate()), 0))  
        --all Active Companies or Companies deactivated within the last 60 days
        OR c.ActiveEnd BETWEEN  DATEADD(MM, DATEDIFF(MM,0,getdate())-2, 0) AND DATEADD(DD,-1,DATEADD(MM, DATEDIFF(MM,0,getdate()), 0))
    )

如果您希望始终包含这些值而不是排除这些值,只需将第一个AND更改为OR

另外,请记住,无论您想为与9999-01-01匹配的日期分配不同的默认值,您都可以使用案例陈述而不仅仅u.ActiveEnd case when u.ActiveEnd = '9999-01-01 00:00:00.000' then '1900-01-01' /* or whatever default you want */ else u.ActiveEnd end