查看完整版本: SQL Server收藏

Stone 2008-7-21 15:52

SQL Server收藏

表T1 如下
ID    Name    CreateDate
1    A      2008-07-21
2    B      2008-07-22
3    C      2008-07-24
4    D      2008-07-24
5    E      2008-07-27
6    F      2008-07-28

假如我需查询的时间区间为2008-07-22 到 2008-07-30
希望能查询到如下的结果[color=#ff0000]:(即当天有数据的情况,统计数据条数,否则为0)[/color]Count      CreateDate
1          2008-07-22
0          2008-07-23
2          2008-07-24
0          2008-07-25
0          2008-07-26
1          2008-07-27
1          2008-07-28
0          2008-07-29
0          2008-07-30


现在问题是,如果该天有数据则能统计,否则不显示条数。
请各位帮忙想个办法!要求只用SQL语句,不用存储过程,游标等
再次感谢

Stone 2008-7-21 15:52

if object_id('tb') is not null
drop table tb
go
create table tb (ID nvarchar(10),Name nvarchar(10),Create_date datetime)
insert tb select
'1',    'A',      '2008-07-21'  union all select
'2',    'B' ,    '2008-07-22'  union all select
'3',    'C' ,    '2008-07-24'  union all select
'4',    'D' ,    '2008-07-24'  union all select
'5',    'E'  ,    '2008-07-27'  union all select
'6',    'F'  ,  '2008-07-28'
if object_id('tday') is not null
  drop table tday
go
declare @starttime datetime
declare @endtime  datetime
set @startTime = '2008-07-22'
set @endTime = '2008-07-30'
create table tday
(
testDate datetime
)
while @startTime <=@endTime
begin
insert into tday values(@startTime)
set @startTime=Dateadd(day,1,@startTime)
end

select a.testdate,isnull(b.cnt,0) from tday a left join (select create_date ,count(*) cnt from tb group by create_date)b on a.testdate=b.create_date
页: [1]
查看完整版本: SQL Server收藏