日期:2014-05-19  浏览次数:20519 次

高分求 sql
数据结构   实际数据如下

date                         count
2007-1-1                   1
2007-1-2                   2
2007-1-4                   3

现在选择   2007-1-1     到     2007-1-4的数据如下

2007-1-1                   1
2007-1-2                   2
2007-1-4                   3


我现在想实现的效果是

2007-1-1                   1
2007-1-2                   2
2007-1-3                   0
2007-1-4                   3

也就是2007-1-3号的数据在数据库是不存在的   我需要在列表的时候造一条2007-1-3   的虚拟数据   count=0

兄弟们看看怎么做




------解决方案--------------------
比较土的方法。。呵呵
先创建个方法,日期的。可以试试。

caerte FUNCTION test(@a as datetime,@b as datetime )
RETURNS @t TABLE(c datetime NOT NULL)
AS
BEGIN

WHILE @a < @b
BEGIN
INSERT INTO @t VALUES(@a)
set @a = DATEADD(day,1,@a)
END
RETURN
END
--调用
select a.c, from test( '2007-1-1 ', '2007-1-4 ') as a left join <table> as b on a.c= b.date


------解决方案--------------------
建一个日期辅助表吧

------解决方案--------------------
嗯..建一张表 tDate(date,count)
数据为:
......
2007-1-1 0
2007-1-2 0
2007-1-3 0
2007-1-4 0
......
select tDate.date,isnull(tYourTable.count,0) from tDate left join tYourTable
on tDate.date = tYourTable.date

------解决方案--------------------
通过表变量来实现
------解决方案--------------------
批准建表^^
------解决方案--------------------
create table ta([date] datetime, [count] int)
insert ta select '2007-1-1 ', 1
union all select '2007-1-2 ', 2
union all select '2007-1-4 ', 3


declare @start datetime,@end datetime
select @start=min(date) from ta
select @end=max(date) from ta
declare @tmp table(date varchar(10))
while convert(varchar(10),@start,120)!> convert(varchar(10),@end,120)
begin
insert @tmp select convert(varchar(10),@start,120)
set @start=@start+1
end
select tb.date,[count]=isnull(count,0)
from @tmp tb left join ta on tb.date=convert(varchar(10),ta.date,120)

(所影响的行数为 1 行)


(所影响的行数为 1 行)


(所影响的行数为 1 行)


(所影响的行数为 1 行)

date count
---------- -----------
2007-01-01 1
2007-01-02 2
2007-01-03 0
2007-01-04 3

(所影响的行数为 4 行)


------解决方案--------------------
加一下注释:
declare @start datetime,@end datetime
select @start=min(date) from ta--定义开始时间
select @end=max(date) from ta--定义结束时间
declare @tmp table(date varchar(10))