
正文
sqlserver补齐,sqlserver自动补全
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
sqlserver 中,如何查询把缺少数据自动填补出来,下图中缺少2013-05-27 19:00:00.000 130.4560000000
问题分析:您要的结果是要每一小时一条记录,补充添写中间间隔一小时以上的记录。并且不另增加记录:
问题解决:找到每一条记录时间加1小时在表中不存在的记录,然后加一小时填入表中,不包括最后(最大的)的时间。
3.语句实现(两种方案):
以下语句可以在每一个缺少的数据后加入一小时后填入,但间隔更大(超过2小时后就不行了):
insert into tablename
select fieldtime=dateadd(hh,1,fieldtime),fieldnum from tablename a
where not exists(select 1 from tablename b where dateadd(hh,1,a.fieldtime)=b.fieldtime)
and a.fieldtime!=(select max(fieldtime) from tablename)--去掉最后的时间
以下方案可以完成补充间隔数小时的记录:将该语句循环执行,直到没有记录更改。
insert into tablename
select fieldtime=dateadd(hh,1,fieldtime),fieldnum from tablename a
where not exists(select 1 from tablename b where dateadd(hh,1,a.fieldtime)=b.fieldtime)
and a.fieldtime!=(select max(fieldtime) from tablename)--去掉最后的时间
while @@rowcount0
select fieldtime=dateadd(hh,1,fieldtime),fieldnum from tablename a where not exists(select 1 from tablename b where dateadd(hh,1,a.fieldtime)=b.fieldtime) and a.fieldtime!=(select max(fieldtime) from tablename)
相关问答
Q1: SQL SERVER自动在前面补0满足10位请问怎么写?
咱们来看:
cast('000000000'+convert(int,code)as varchar(20))
首先:
convert(int,code) :你把code 转为 int
然后
'000000000'+convert(int,code)我估计sqlserver肯定把表达式作为数字相加了,那么0000...的相加就没有作用了。
最后
就不是你要的结果了。
大致应该这样:
SELECT
right(cast('000000000'+rtrim(code) as varchar(20)),10),code,
id,pydate,isnull(lzdate,'9999-12-31'),0
FROM zlemployee
Q2: sqlserver数据库间断日期补全查询
DECLARE @T TABLE(日期 DATE,金额 INT)
DECLARE @D1 DATE,@D2 DATE
SELECT @D1=MIN(日期),@D2=MAX(日期) FROM A表
WHILE @D1=@D2
BEGIN
INSERT INTO @T VALUES(@D1,0)
SET @D1=DATEADD(DAY,1,@D1)
END
SELECT 日期,金额 FROM A表
UNION ALL
SELECT * FROM @T WHERE 日期 NOT IN(SELECT 日期 FROM A表)






