求一条效率较高的SQL语句
table : dbo.sa_userinfo
字段:id --- 自增量
date --- 时间
GUID --- GUID
本人想求的是 求出某一天(eg:2006-12-15)范围内出现的所有guid ,然后求出这些GUID在2006-12-15前最近一次出现的时间 距离现在的天数
之前是在程序中实现 :
1。先求出(2006-12-15)这一天出现的所有GUID,循环记录集得出每个具体的GUID
select distinct(GUID ), date from sa_userinfo where date = '2006-12-15 '
2.再根据记录集循环出来的结果,求每个GUID上次出现到现在的天数
select top 1 datediff(Day,date, '2006-12-15 ') AS daynum from sa_userinfo where guid = 'xxxxxx ' and sa_userinfo.[date],20 < '2006-12-15 ' order by id desc
但是这样效率极低,根本不具可行性,如果当天有1000条记录,当天之前有10000条记录,就要执行1000X10000次 所以请教下大家或者换种思路
在此小弟谢过
------解决方案--------------------select a.GUID,max(b.date) as date
from
(select GUID from sa_userinfo where date = '2006-12-15 ')a left join
sa_userinfo b on a.GUID = b.GUID
where b.date < '2006-12-15 '
------解决方案--------------------select distinct(GUID),[date] into #tmp from sa_userinfo where [date]= '2006-12-15 '
select guid,max([date]) [date] into #tmp1 from sa_userinfo where [date] < '2006-12-15 ' group by guid
select a.guid,datediff(day,b.date,a.date) num from #tmp a Inner Join #tmp1 b On a.guid=b.guid