抱歉标题困惑。请告诉,是否可以通过数据库请求来完成。假设我们有下表
ind_id name value date
----------- -------------------- ----------- ----------
1 a 10 2010-01-01
1 a 20 2010-01-02
1 a 30 2010-01-03
2 b 10 2010-01-01
2 b 20 2010-01-02
2 b 30 2010-01-03
2 b 40 2010-01-04
3 c 10 2010-01-01
3 c 20 2010-01-02
3 c 30 2010-01-03
3 c 40 2010-01-04
3 c 50 2010-01-05
4 d 10 2010-01-05
我需要查询所有行以包含给定日期的每个 ind_id
一次,如果给定日期没有 ind_id
,则取最近的较低日期,如果没有任何更早的日期,然后返回 ind_id + name(name/ind_id 对相等)和空值。
例如,日期是 2010-01-04,我希望得到以下结果:
ind_id name value date
----------- -------------------- ----------- ----------
1 a 30 2010-01-03
2 b 40 2010-01-04
3 c 40 2010-01-04
4 d NULL NULL
如果可能的话,如果有人帮助我构建查询,我将不胜感激。我正在使用 SQL Server 2008。
最佳答案
检查这个 SQL FIDDLE DEMO
with CTE_test
as
(
select int_id,
max(date) MaxDate
from test
where date<='2010-01-04 00:00:00:000'
group by int_id
)
select A.int_id, A.[Value], A.[Date]
from test A
inner join CTE_test B
on a.int_id=b.int_id
and a.date = b.Maxdate
union all
select int_id, null, null
from test
where int_id not in (select int_id from CTE_test)
关于sql - 选择值等于给定值或更低且最接近给定值的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15687398/