2016-07-14 40 views
0

我有一個客戶和門票的數據庫。門票日期範圍從2007年到2017年的將來日期。我想運行一個查詢,爲我提供過去最近的門票和未來最近的門票。如何根據SQL中的GETDATE()輸出最後和下一個日期

我最初下面的查詢給了我他們的第一次門票和他們的出票日期最遠的未來 - 但我想沿着線的東西:

MAX(EVENTDATE),其中(EVENTDATE < GETDATE()) AS LastDate和類似MIN(eventdate)where(eventdate < getdate())AS NEXTDate但我真的不知道如何。據推測它會涉及子查詢?

SELECT  MAX(Dwh.DimEvents.devEventDate) AS Last_Show, MIN(Dwh.DimEvents.devEventDate) AS First_Show, Dwh.DimClients.dcClientCode, Dwh.DimClients.dcFirstName, Dwh.DimClients.dcLastName 
FROM  Dwh.FactTickets LEFT OUTER JOIN 
        Dwh.DimClients ON Dwh.DimClients.dcClientGUID = Dwh.FactTickets.ftClientGuid LEFT OUTER JOIN 
        Dwh.DimEvents ON Dwh.DimEvents.devGuid = Dwh.FactTickets.ftEventGuid LEFT OUTER JOIN 
        Dwh.DimShows ON Dwh.DimEvents.devShowGuid = Dwh.DimShows.dshGuid 
WHERE  (Dwh.FactTickets.ftTicketStatus = 1) 
GROUP BY Dwh.DimClients.dcClientCode, Dwh.DimClients.dcFirstName, Dwh.DimClients.dcLastName 

回答

0

嘗試這樣的事情..不要忘記測試查詢的性能..

SELECT 
(
Select MAX(DimEvents.devEventDate) 
from DimEvents INNER JOIN FactTickets ON DimEvents.devGuid = FactTickets.ftEventGuid 
and DimClients.dcClientGUID = FactTickets.ftClientGuid and DimEvents.devEventDate < GetDate() 
and FactTickets.ftTicketStatus = 1 
) AS MostRecentPast, 

(
Select MIN(DimEvents.devEventDate) 
from DimEvents INNER JOIN FactTickets ON DimEvents.devGuid = FactTickets.ftEventGuid 
and DimClients.dcClientGUID = FactTickets.ftClientGuid and DimEvents.devEventDate > GetDate() 
and FactTickets.ftTicketStatus = 1 
) AS ClosestInFuture, 
DimClients.dcClientCode, DimClients.dcFirstName, DimClients.dcLastName 
FROM DimClients 
GROUP BY DimClients.dcClientCode, DimClients.dcFirstName, DimClients.dcLastName 
+0

嗨Jawad,這似乎沒有工作,因爲它一直告訴我,'Dwh.FactTickets.ftEventGuid'在選擇列表中是無效的,因爲它不包含在聚合函數或GROUP BY子句中。我嘗試在Group By中添加,但之後它只列出了每個人的每個事件 – wolfgang

+0

我不認爲您需要Group By,因爲我們已經將聚合函數轉換爲子選擇。由於我沒有完整的數據庫結構,因此無法在此處進行測試。 –

+0

不幸的是,雖然刪除Group By行允許它運行,它仍然給我所有的票日期,而不僅僅是最後一個和下一個。 – wolfgang

0

你可以得到日期最近的過去的機票和不久的將來,機票就像這樣:

DECLARE @TargetDate datetime 
SELECT @TargetDate = getdate() 

SELECT MAX(TimeColumn) FROM table WHERE TimeColumn < @TargetDate 

SELECT MIN(TimeColumn) FROM table WHERE TimeColumn > @TargetDate 

然後,您可以嵌入這些子查詢,像這樣:

SELECT 
    TicketColumn1, 
    TicketColumn2, 
    TicketColumn3, 
    etc 
FROM 
    TicketTable 
WHERE 
    TimeColumn = (SELECT MAX(TimeColumn) FROM table WHERE TimeColumn < @TargetDate) 
    or TimeColumn = (SELECT MIN(TimeColumn) FROM table WHERE TimeColumn > @TargetDate) 
相關問題