id uid date
1 1 2014-01-01
2 2 2014-01-01
3 1 2014-01-01
4 1 2014-01-03
5 2 2014-01-04
6 1 2014-01-04
7 1 2014-01-06
8 2 2014-01-06
9 1 2014-01-07
现要得到在2014-01-01 到 2014-01-07的如下记录
date count
2014-1-1 3
2014-1-2 0
2014-1-3 1
2014-1-4 2
2014-1-5 0
2014-1-6 2
2014-1-7 1
还需要得出
date count
星期三 3
星期四 0
星期五 1
星期六 2
星期日 0
星期一 2
星期二 1
SQL表中获取时间段里每一天的数据,如果表里没有这一天的记录数据就为0
不知道那位大神能帮我解决这个问题,小弟不胜感激。
------解决方案--------------------
create table test (id int,[uid] int,[date] datetime)
insert test
select 1,1,'2014-01-01' union all
select 2,2,'2014-01-01' union all
select 3,1,'2014-01-01' union all
select 4,1,'2014-01-03' union all
select 5,2,'2014-01-04' union all
select 6,1,'2014-01-04' union all
select 7,1,'2014-01-06' union all
select 8,2,'2014-01-06' union all
select 9,1,'2014-01-07'
DECLARE @start datetime
DECLARE @end datetime
DECLARE @sint int
DECLARE @eint int
set @start='2014-01-01'
set @end='2014-01-07'
set @sint=DATEPART(day,@start)
set @eint=DATEdiff(DAY,@start,@end)
set language N'Simplified Chinese'
;WITH TT AS (
SELECT number
FROM master..spt_values
WHERE type = 'P'
AND number BETWEEN @sint-1 AND @eint
)
select b.[date],
[count]=isnull(a.[count],0),
星期=datename(WEEKDAY, b.[date])
from (
select [date],
[count]=COUNT(*)
from test
group by [date]
) a
right join (
select [date]=DATEADD(DAY,TT.number,@start)
from TT
) b
ON a.[date]=b.[date]
------解决方案--------------------
把楼上几位大神的结果整理了下。。
create table #test (id int,[uid] int,[date] datetime)
insert #test
select 1,1,'2014-01-01' union all
select 2,2,'2014-01-01' union all
select 3,1,'2014-01-01' union all
select 4,1,'2014-01-03' union all
select 5,2,'2014-01-04' union all
select 6,1,'2014-01-04' union all
select 7,1,'2014-01-06' union all
select 8,2,'2014-01-06' union all
select 9,1,'2014-01-07'
CREATE table #tempDate
(
stat_day varchar(10)
)
CREATE clustered index tempDate_Index1 on #tempDate (stat_day)
declare @time_temp datetime
set @time_temp = '2014-01-01'
while @time_temp < '2014-01-07'
begin
insert into #tempDate (stat_day) values (CONVERT(varchar(10),@time_temp,121))
set @time_temp= dateadd(d,1,@time_temp)
end
Select
Count(#test.[date]),
#tempDate.stat_day
From
#tempDate
Left Outer Join #test On #tempDate.stat_day = #test.[date]
Group By
#tempDate.stat_day
Select
Count(#test.[date]),
datename(WEEKDAY, #tempDate.stat_day)
From
#tempDate
Left Outer Join #test On #tempDate.stat_day = #test.[date]
Group By
#tempDate.stat_day
IF object_id('tempdb..#test') is not null