我在ms sql server中有一个名为table1的表,如果我执行的话 选择时间,显示表1中的数据
time |data
-------|------
08:00 |a
10:00 |b
12:00 |c
我需要查询一段时间,所有时间增加1小时,结果必须如下所示:
time |data
-------|------
08:00 | a
09:00 | empty
10:00 |b
11:00 | empty
12:00 |c
13:00 | empty
答案 0 :(得分:0)
请尝试:
declare @mn time, @mx time
select @mn=MIN([time]), @mx=MAX([time]) from @tbl
;with T as(
select
[time],
data
from tbl
where [time]=@mn
union all
select DATEADD(hour, 1,T.[time]),
(select b.data from tbl b where DATEADD(hour, 1,T.[time])=b.[time])
from T
where [time]<=@mx)
select
time,
ISNULL(data, 'empty') data
from T
答案 1 :(得分:0)
我通过首先生成您想要的列表(在本例中为时间)然后使用left outer join
来组合原始数据来处理这些类型的问题。
以下使用递归CTE生成列表。它首先确定时间的最小值和最大值,然后使用递归生成列表:
with minmax as (
select min(time) as mintime, max(time) as maxtime
from table t
),
times(thetime, maxtime) as (
select mintime as thetime, maxtime
from minmax
union all
select dateadd(hour, 1, thetime), maxtime
from times
where thetime < maxtime
)
select times.thetime, t.data
from times left outer join
table1 t
on t.time = times.thetime;
Here是一个证明它的SQL小提琴。