2016-07-28 56 views
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 
    -- 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'列值爲整個表中的'9999-01-01 00:00:00.000'在UsersCompanies表中。如何處理where子句中的默認值'9999-01-01 00:00:00.000'

我不理解如何編寫一個條件來處理/管理這個默認值以及我在上面的where子句中。

+2

哪個RDBMS是本作的日期?請添加一個標籤來指定您是使用'mysql','postgresql','sql-server','oracle'還是'db2' - 或者其他的東西。 –

+0

默認列值對查詢中的邏輯有什麼影響?據推測列'9999'默認值會失敗'WHERE'子句,但再次不會是預期的行爲? –

+0

它的SQL服務器, – Kumar

回答

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)) 
    ) 

如果你想總是包含,而不是排除這些價值,只是改變了第一ANDOR

另外請記住,任何你想要一個不同的默認值分配給符合9999-01-01您可以使用一個case語句,而不是僅僅u.ActiveEndcase when u.ActiveEnd = '9999-01-01 00:00:00.000' then '1900-01-01' /* or whatever default you want */ else u.ActiveEnd end

+0

非常感謝您的幫助,您節省了我的時間 – Kumar

相關問題