1

编辑:问题陈述:选择 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)
4

2 回答 2

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
于 2013-08-01T05:18:50.253 回答
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
于 2013-08-01T05:36:19.080 回答