日期:2014-05-17  浏览次数:20462 次

请教SQL按日期排列连续显示问题
有以下表数据。里面的日期是不连贯的,断断续续的。
现需求如下,按日期显示数据。表里面没有的日期也是显示出来,金额显示为0。
求指点SQL写法,谢谢各位!

例如原始数据如下:

城市   金额      日期
广州   20000    06-20
广州   30000   06-22
广州   23000   06-24
广州   5000    06-28

希望结果如下:

城市   金额      日期
广州   20000   06-20
广州   0         06-21
广州   20000    06-22
广州   0          06-23
广州   23000   06-24
广州   0          06-25
广州   0          06-26
广州   0          06-27
广州   5000    06-28
------最佳解决方案--------------------

create table cb
(城市 varchar(6),
 金额 int,
 日期 varchar(6))
 
insert into cb 
 select '广州', '20000', '06-20' union all
 select '广州', '30000', '06-22' union all
 select '广州', '23000', '06-24' union all
 select '广州', '5000', '06-28'


select isnull(b.城市,'广州') '城市',
       isnull(b.金额,0) '金额',
       a.qd '日期'
from
(select right(convert(varchar,dateadd(d,number,
        (select '2012-'+min(日期) from cb)),23),5) 'qd'
 from master.dbo.spt_values
 where [type]='P' and number<=
 (select datediff(d,'2012-'+min(日期),'2012-'+max(日期)) from cb)
) a
left join cb b on a.qd=b.日期
 
/*
城市     金额         日期
------ ----------- ----------
广州     20000       06-20
广州     0           06-21
广州     30000       06-22
广州     0           06-23
广州     23000       06-24
广州     0           06-25
广州     0           06-26
广州     0           06-27
广州     5000        06-28

(9 row(s) affected)
*/

------其他解决方案--------------------
--日期表
declare @begindate date='2012-6-1'
declare @enddate date='2012-6-30'
declare @datetb(DT date)
while @begindate<=@enddate
begin
insert into @datetb
select @begindate
set @begindate=@begindate+1
end
--查询
select b.城市,isnull