0

我需要在一个 SQL 查询中获取所有优惠的具体日期。我不知道如何在这些条件下做到这一点:

  1. 如果有活动报价,我需要活动期间的开始/结束日期
  2. 如果有过期的报价,我需要最后的开始/结束日期
  3. 如果有未来的报价,我需要第一个开始/结束日期

餐桌优惠:

OfferID Name
10      Current Offer
20      Expired Offer
30      Coming Offer

表 OfferDates:(NULL = 无限优惠)

OfferID StartDate   EndDate
10      2000-01-01  2009-12-31
10      2010-01-01  NULL        //Need this (1.)
20      1900-01-01  1900-12-31
20      1901-01-01  1901-12-31  //Need this (2.)
30      2030-01-01  2030-12-31  //Need this (3.)
30      2031-01-01  NULL

这应该是结果:

OfferID Name    StartDate   EndDate
10      Current 2010-01-01  NULL
20      Expired 1901-01-01  1901-12-31
30      Coming  2030-01-01  2030-12-31

这将为我提供有效的报价 (1.):

SELECT o.Name, d.StartDate, d.EndDate FROM Offer AS o
LEFT JOIN OfferDates AS d ON o.OfferID = d.OfferID
WHERE d.StartDate <= GETDATE() AND (d.EndDate IS NULL OR d.EndDate > GETDATE())

我希望有人能帮助我!

谢谢!

4

1 回答 1

0

我做到了!

SELECT DISTINCT 
o.Name,  
ISNULL(curr.StartDate, ISNULL(fut.StartDate, hist.StartDate)) AS 'StartDate', --Only get "NOT NULL-StartDate"
ISNULL(curr.EndDate, ISNULL(fut.EndDate, hist.EndDate)) AS 'EndDate' --Only get "NOT NULL-EndDate"

FROM Offer AS o

-- Current
LEFT JOIN (SELECT * FROM OfferDates WHERE StartDate <= GETDATE() AND (EndDate IS NULL OR  EndDate > GETDATE())) AS curr ON (o.OfferID = curr.OfferID)

-- Expired
LEFT JOIN (SELECT OfferID, MAX(EndDate) AS EndDate FROM OfferDates WHERE EndDate < GETDATE()  AND EndDate IS NOT NULL GROUP BY OfferID)AS tmpHist ON (o.OfferID = tmpHist.OfferID)
LEFT JOIN (SELECT * FROM OfferDates WHERE OfferID NOT IN (SELECT OfferID FROM OfferDates WHERE EndDate >= GETDATE() OR EndDate IS NULL)) AS hist ON (tmpHist.OfferID = hist.OfferID AND tmpHist.EndDate = hist.EndDate)

-- Future
LEFT JOIN (SELECT OfferID, MIN(StartDate) AS StartDate FROM OfferDates WHERE StartDate > GETDATE() GROUP BY OfferID) AS tmpFut ON (o.OfferID = tmpFut.OfferID)
LEFT JOIN (SELECT * FROM OfferDates WHERE OfferID NOT IN (SELECT OfferID FROM OfferDates WHERE StartDate <= GETDATE())) AS fut ON (tmpFut.OfferID = o.OfferID AND tmpFut.StartDate = fut.StartDate)                   
于 2013-08-15T12:07:41.930 回答