我目前正致力于围绕优惠构建SQL查询。
基本上,优惠有开始和结束日期。
场景1:用户仅指定日期。
解决方案1:显示从当天开始或过去的所有优惠。
场景2:用户仅指定TO日期。
解决方案2:所有报价均显示在该指定日期之前或之前结束。
场景3:用户指定要搜索的TO和FROM日期。
解决方案3的问题如下。
优惠 - 从01-01-2012至03-03-2012
搜索 - 从01-01-2012到02-02-2012
要约应在查询中返回,因为它介于两个搜索值之间。
我当前的查询在下面,但是它不能按要求运行。
CREATE PROCEDURE [dbo].[GetAllOffers]
@retailer_id BIGINT,
@opt_in BIGINT,
@use_once BIGINT,
@from_date DATETIME,
@to_date DATETIME
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
SET NOCOUNT ON;
SELECT retr.Name,
reco.Headline,
reco.isOptIn,
reco.isUseOnce,
reco.DateValidFrom,
reco.DateExpires,
reco.Id AS OfferId
FROM RetailerCoupon reco
INNER JOIN Retailer retr
ON reco.RetailerId = retr.Id
WHERE (reco.RetailerId = @retailer_id
OR @retailer_id IS NULL)
AND (reco.isOptIn = @opt_in
OR @opt_in IS NULL)
AND (reco.isUseOnce = @use_once
OR @use_once IS NULL)
AND (reco.DateValidFrom >= @from_date
OR @from_date IS NULL)
AND (reco.DateExpires <= @to_date
OR @to_date IS NULL)
ORDER BY retr.Name
END
GO
请注意方案1&amp; 2上面的查询覆盖了2,这导致了问题。
史蒂芬
答案 0 :(得分:0)
我仍在测试这个并尝试改进它,但这是否符合您的需求:
一些测试数据
declare @tmp table (offer nvarchar(30), startTime datetime, endTime datetime)
insert @tmp values ('Offer_1','2012-04-01','2012-04-10'),('Offer_2','2012-04-05','2012-04-15'),('Offer_3','2012-04-10','2012-04-20'),('Offer_!!!','2012-01-01','2012-03-03')
Offer_!!!
就是上面的例子
select *
from @tmp
where
-- Scenario1
(@from_date <= startTime AND @to_date IS NULL)
OR -- Scenario2
(@from_date IS NULL AND @to_date <= endTime)
OR -- Scenario3
((@from_date BETWEEN startTime AND endTime)
AND
(@to_date BETWEEN startTime AND endTime))
给出:
-- Scenario 1
EXEC GetAllOffers @from_date = '2012-04-01'
, @to_Date = null
offer startTime endTime
------------------------------ ----------------------- -----------------------
Offer_1 2012-04-01 00:00:00.000 2012-04-10 00:00:00.000
Offer_2 2012-04-05 00:00:00.000 2012-04-15 00:00:00.000
Offer_3 2012-04-10 00:00:00.000 2012-04-20 00:00:00.000
-- Scenario 2
EXEC GetAllOffers @from_date = null
, @to_Date = '2012-01-09'
offer startTime endTime
------------------------------ ----------------------- -----------------------
Offer_1 2012-04-01 00:00:00.000 2012-04-10 00:00:00.000
Offer_2 2012-04-05 00:00:00.000 2012-04-15 00:00:00.000
Offer_3 2012-04-10 00:00:00.000 2012-04-20 00:00:00.000
Offer_!!! 2012-01-01 00:00:00.000 2012-03-03 00:00:00.000
-- Scenario 3
EXEC GetAllOffers @from_date = '2012-01-01'
, @to_Date = '2012-02-02'
offer startTime endTime
------------------------------ ----------------------- -----------------------
Offer_!!! 2012-01-01 00:00:00.000 2012-03-03 00:00:00.000
在我看来,您的要求中存在一些非常大的漏洞,但这似乎与您在场景中提出的要求相同