日期:2014-05-18 浏览次数:20488 次
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]( [courseID] int, [studentID] int, [startTime] datetime ) go insert [test] select 1,1,'2012-07-16' union all select 2,1,'2012-07-16' union all select 3,1,'2012-07-17' union all select 4,1,'2012-07-22' go declare @StartDate datetime declare @EndDate datetime set @StartDate='2012-07-16' set @EndDate='2012-07-22' ;with t as( select DATEADD(DD,number,@StartDate) as Dtes from master..spt_values where type='p' and number between 0 and DATEDIFF(DD,@StartDate,@EndDate) ) select '星期'+ltrim(DATEPART(W,Dtes)) as [week], SUM(case when [startTime] is null then 0 else 1 end) as [count] from t left join test on t.Dtes=test.startTime group by Dtes order by 2 desc /* week count ------------------------------ 星期2 2 星期1 1 星期3 1 星期6 0 星期4 0 星期7 0 星期5 0 */
------解决方案--------------------
select a.wd,count(courseID) from ( select '星期一' as wd union all select '星期二' union all select '星期三' union all select '星期四' union all select '星期五' union all select '星期六' union all select '星期日' ) a left join courseInfo c on a.wd=datename(weekday ,c.startTime) group by a.wd