我需要在一个SQL查询中获取所有商品的具体日期。我不知道如何在这些条件下做到这一点:
表格优惠:
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())
我希望有人可以帮助我!
谢谢!
答案 0 :(得分: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)