编辑: 问题陈述: 在3月初到5月底之间选择所有SIIIS和SULLS数据
对于SIIIS中的每个“XFFF”,查找SULLS中“XFFF”中的任何匹配,其中SULLS中的“Start_Time”位于SIIIS中的“Case_Create”之后,“Start_Time”和“Case_Create”之间的时差小于3小时。 选择时间差最小的匹配
select
si.XFFF xfff,
DATEDIFF(hour, si.CASE_CREATE, su.START_TIME) diffInhours
from siiis si inner join sulls su on si.xfff= su.xfff
where
((si.CASE_CREATE BETWEEN '20130301' AND '20130531') and (su.START_TIME between '20130301'AND '20130531'))
and
(su.START_TIME > si.CASE_CREATE) and
(DATEDIFF(hour, si.CASE_CREATE, su.START_TIME) < 3 and DATEDIFF(hour, si.CASE_CREATE, su.START_TIME) > 0)
答案 0 :(得分:0)
试试此代码。基本上它应该做的是它按DATEDIFF(hour, si.CASE_CREATE, su.START_TIME)
按升序排序然后选择第一个1.它没有经过测试所以我解释了逻辑。
SELECT TOP 1
si.num_phone Phone,
su.start_time sulstarrtTime ,
si.CASE_CREATE siStartTime,
DATEDIFF(hour, si.CASE_CREATE, su.START_TIME) diffInhours
from siiis si inner join sulls su on si.num_phone = su.num_phone
where
((si.CASE_CREATE BETWEEN '20130301' AND '20130531') and (su.START_TIME between '20130301'AND '20130531'))
and
(su.START_TIME > si.CASE_CREATE) and
(DATEDIFF(hour, si.CASE_CREATE, su.START_TIME) < 3 and DATEDIFF(hour, si.CASE_CREATE, su.START_TIME) > 0)
order by DATEDIFF(hour, si.CASE_CREATE, su.START_TIME) ASC
答案 1 :(得分:0)
试图清理和修复你的代码,应该在sqlserver 2008+上运行,datediff不会给你几小时的差异(非常常见的误解),所以我采取了不同的方法:
select
si.num_phone Phone,
su.start_time sulstarrtTime ,
si.CASE_CREATE siStartTime,
datediff(hour, 0, su.START_TIME - si.CASE_CREATE) diffInhours
from siiis si
cross apply
(select top 1 * from sulls su
where
si.xfff= su.xfff
and su.START_TIME > si.CASE_CREATE
-- less than 3 hours difference
and dateadd(hour, 3, si.CASE_CREATE) > su.START_TIME
-- more than 1 hour difference your code indicated you needed this, your text said otherwise
--and dateadd(hour, 1, si.CASE_CREATE) <= su.START_TIME
order by START_TIME
) su
WHERE si.CASE_CREATE BETWEEN '20130301' AND '20130531' -- you are not including all of may