--统计某月份周情况 没有的补0
if object_id('temp_tb') is not null
drop table temp_tb
create table temp_tb
([ID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[test_values] int NULL,
[time] datetime null,
);
go
insert into temp_tb([test_values],[time])
select 3,'2009-2-1 10:12:30' union all
select 5,'2009-2-5 09:20:23' union all
select 6,'2009-2-6 11:21:34' union all
select 7,'2009-2-8 12:22:12' union all
select 2,'2009-2-10 16:45:25' union all
select 3,'2009-2-13 13:21:14' union all
select 5,'2009-2-15 15:58:09' union all
select 1,'2009-2-15 08:35:47' union all
select 1,'2009-2-15 09:13:07' union all
select 9,'2009-2-15 09:15:04'
select * from temp_tb
SELECT
A.[Week],
ISNULL(COUNT(B.test_values),0) AS num
FROM (
SELECT
datepart(week,dateadd(week,0,dateadd(day,number,'2009-02-01'))) AS [Week]
FROM master.dbo.spt_values
WHERE type='p' AND number BETWEEN 0 AND 27
GROUP BY datepart(week,dateadd(week,0,dateadd(day,number,'2009-02-01')))
) AS A
LEFT JOIN temp_tb AS B
ON A.[Week]=DATEPART(week,time)
GROUP BY A.[Week]
SELECT DATEPART(WEEK,'2009-10-30 12:15:32.1234567 +05:10') --44周
/*
ID test_values time
--------------------------------------- ----------- -----------------------
1 3 2009-02-01 10:12:30.000
2 5 2009-02-05 09:20:23.000
3 6 2009-02-06 11:21:34.000
4 7 2009-02-08 12:22:12.000
5 2 2009-02-10 16:45:25.000
6 3 2009-02-13 13:21:14.000
7 5 2009-02-15 15:58:09.000
8 1 2009-02-15 08:35:47.000
9 1 2009-02-15 09:13:07.000
10 9 2009-02-15 09:15:04.000
(10 行受影响)
Week num
----------- -----------
6 3
7 3
8 4
9 0
*/
--1、得出一天的时间段记录。
select 时间段=ltrim(a.number)+':00-'+ltrim(b.number)+':00'
from master..spt_values a,master..spt_values b
where a.type='p'and b.type='p'
and a.number between 1 and 24
and b.number between 1 and 24
and a.number=b.number-1
/*
时间段
-------------------------------
1:00-2:00
2:00-3:00
3:00-4:00
4:00-5:00
5:00-6:00
6:00-7:00
7:00-8:00
8:00-9:00
9:00-10:00
10:00-11:00
11:00-12:00
12:00-13:00
13:00-14:00
14:00-15:00
15:00-16:00
16:00-17:00
17:00-18:00
18:00-19:00
19:00-20:00
20:00-21:00
21:00-22:00
22:00-23:00
23:00-24:00
(23 行受影响)
*/
--2、通过1个select语句某个月的所有日期记录
declare @date datetime
set @date='2009-11-23'
select [day]=ltrim(year(@date))+right(100+month(@date),2)+right('0'+ltrim(number),2)
from master..spt_values
where type='p'
and number >=1
and number <= datediff(dd,@date,dateadd(month,1,@date))
/*
day
--------------------
20091101
20091102
20091103
20091104
20091105
20091106
20091107
20091108
20091109
20091110
20091111
20091112
20091113
20091114
20091115
20091116
20091117
20091118
20091119
20091120
20091121
20091122
20091123
20091124
20091125
20091126
20091127
20091128
20091129
20091130
(30 行受影响)
*/