avatar
k*e
1
a table like following:
Name Date
a 12/1/2006
b 12/1/2006
a 12/5/2006
a 12/6/2006
b 12/7/2006
b 12/20/2006
我想对每一个Name,找出Date最接近的两个记录。
上面的例子应该返回
a 12/5/2006
a 12/6/2006
b 12/1/2006
b 12/7/2006
用sql应该如何实现?
avatar
l*n
2
先单个找出来,然后再比较?

【在 k***e 的大作中提到】
: a table like following:
: Name Date
: a 12/1/2006
: b 12/1/2006
: a 12/5/2006
: a 12/6/2006
: b 12/7/2006
: b 12/20/2006
: 我想对每一个Name,找出Date最接近的两个记录。
: 上面的例子应该返回

avatar
c*d
3
必须一个sql statement?

【在 k***e 的大作中提到】
: a table like following:
: Name Date
: a 12/1/2006
: b 12/1/2006
: a 12/5/2006
: a 12/6/2006
: b 12/7/2006
: b 12/20/2006
: 我想对每一个Name,找出Date最接近的两个记录。
: 上面的例子应该返回

avatar
O*K
4
select Name, Date
from (
select top 1 T1.Name, T1.Date, min(T2.Date - T1.Date) as DateDiff
from TableName as T1, TableName as T2
where T1.Name = T2.Name
and T1.Date < T2.Date
group by T1.Name, T1.Date
order by min(T2.Date - T1.Date) ) as A
union
select Name, Date + DateDiff as Date
from (
select top 1 T1.Name, T1.Date, min(T2.Date - T1.Date) as DateDiff
from TableName as T1, TableName as T2
where T1.Name = T2.Name
and T1.Date < T2.Date
group by T1.Name, T1.Date
order by min(T2.Date - T1.Date) )
avatar
w*n
5
run 的结果是:
a 2006-12-05 00:00:00.000
a 2006-12-06 00:00:00.000
b 呢?

【在 O**K 的大作中提到】
: select Name, Date
: from (
: select top 1 T1.Name, T1.Date, min(T2.Date - T1.Date) as DateDiff
: from TableName as T1, TableName as T2
: where T1.Name = T2.Name
: and T1.Date < T2.Date
: group by T1.Name, T1.Date
: order by min(T2.Date - T1.Date) ) as A
: union
: select Name, Date + DateDiff as Date

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。