请求您的帮助,以便从下面设定的日期获得以下结果
我有以下结果集
CampaignName Matchfrom MatchTo
a 08-09-2013 07-11-2013
a 10-09-2013 10-11-2013
a 08-11-2013 07-01-2014
a 09-11-2013 08-01-2014
上面的set在matchfrom date列上排序。第一行将被视为主
现在查询应该过滤掉matchfrom在master的日期范围内的行。
这,我实现了使用自我加入。但现在第三行完全超出了主人的范围(第一行)。现在应该将其视为主数据,它应该过滤掉第4行。
最终结果集如下所示,标记为通过和失败
CampaignName Matchfrom MatchTo
a 08-09-2013 07-11-2013 PASS
a 10-09-2013 10-11-2013 FAIL
a 08-11-2013 07-01-2014 PASS
a 09-11-2013 08-01-2014 FAIL
有人可以告诉我这个
答案 0 :(得分:0)
有了你的数据,你将不得不做更多的擦洗,但下面的代码应该让你朝着正确的方向。你必须要小心,因为你的“主记录”中的MatchFrom和MatchTo与你的所有其他数据相反。
CREATE TABLE #tmpCampaign(
CampaignName varchar(1),
Matchfrom Date,
MatchTo Date
)
INSERT INTO #tmpCampaign VALUES
('a','08-09-2013','07-11-2013'),
('a','10-09-2013','10-11-2013'),
('a','08-11-2015','07-01-2014'),
('a','09-11-2013','08-01-2014')
;WITH Campaign AS(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY campaignName ORDER BY MatchFrom) as CampRank
FROM #tmpCampaign)
SELECT c1.*, c2.MatchFrom as MasterFrom, c2.MatchTo as MasterTo,
CASE WHEN c1.Matchfrom >= c2.MatchFrom AND c1.Matchfrom <= c2.MatchTo THEN 'Pass'
ELSE 'Fail' END as PassFail
FROM Campaign as c1
JOIN Campaign as c2
ON c1.CampaignName = c2.CampaignName and c2.CampRank = 1
答案 1 :(得分:0)
可能是在发生日期重复时出现问题但是对于你的结果集我已经选择了datekey并根据它完成了分区以实现结果
;With Cte as
(select Campaignname,
matchfrom,
matchto,
ROW_number()OVER(PARTITION BY right(matchfrom, len(matchfrom) - charindex('-', matchfrom) - 3)ORDER BY Campaignname)RN
from #tmpCampaign )
select Campaignname,
matchfrom,
matchto,
Case when RN = 1 then 'Pass' ELSE 'Fail' END
from Cte