一道sql题，不知道有好解决方法没有?

create table tb(ID int,Time datetime)
insert tb select 1,'2005/01/24 16:20'
union all select 2,'2005/01/23 22:45'
union all select 3,'2005/01/23 0:30'
union all select 4,'2005/01/21 4:28'
union all select 5,'2005/01/20 13:22'
union all select 6,'2005/01/19 20:30'
union all select 7,'2005/01/19 18:23'
union all select 8,'2005/01/18 9:14'
union all select 9,'2005/01/18 18:04'
go

--------------         -----     -----   -----     -----  -----  ------ ----     ------
[5pm - 9pm)       0        1        2         0       0       0      0       3
[9pm - 1am)       0        0        0         0       0       0      2       2
[1am - 4am)       0        0        0         0       0       0      0       0
[4am - 8:30am) 0        0        0         0       1        0     0       1
[8:30am - 1pm) 0       1         0         0       0        0     0       1
[1pm - 5pm)      1        0         0        1       0        0     0       2
Total                   1         2        2        1        1        0     2       9

select y as '所过时段',
mon=sum(isnull((case when x=2 then z end),0)),
Tue=sum(isnull((case when x=3 then z end),0)),
Wed=sum(isnull((case when x=4 then z end),0)),
Thu=sum(isnull((case when x=5 then z end),0)),
Fri=sum(isnull((case when x=6 then z end),0)),
Six=sum(isnull((case when x=7 then z end),0)),
Sun=sum(isnull((case when x=1 then z end),0)),
Total=sum(z)
from
(select x,y,count(*) z
from
(select x=DATEPART(dw,time),
y=case
when  DATEPART(hh,time)>=17 and DATEPART(hh,time)<21 then '[5pm - 9pm)'
when  ((DATEPART(hh,time)>=4 and DATEPART(hh,time)<8) or (DATEPART(hh,time)=8 and DATEPART(n,time)<30)) then '[4am - 8:30am)'
when  DATEPART(hh,time)<13 and DATEPART(hh,time)>8 or(DATEPART(hh,time)=8 and DATEPART(mi,time)>=30) then '[8:30am - 1pm)'
when  DATEPART(hh,time)>=13 and DATEPART(hh,time)<17 then '[1pm - 5pm)'
when  (DATEPART(hh,time)>=21 or DATEPART(hh,time)<1) then '[9pm - 1am)'
when  DATEPART(hh,time)>=1 and DATEPART(hh,time)<4 then '[1am - 4am)'
end
from tb) b
group by x,y) c
group by y
union all
select 'Total' as '所过时段',
mon=(select count(*) from tb where DATEPART(dw,time)=2),
Tue=(select count(*) from tb where DATEPART(dw,time)=3),
Wed=(select count(*) from tb where DATEPART(dw,time)=4),
Thu=(select count(*) from tb where DATEPART(dw,time)=5),
Fri=(select count(*) from tb where DATEPART(dw,time)=6),
Six=(select count(*) from tb where DATEPART(dw,time)=7),
Sun=(select count(*) from tb where DATEPART(dw,time)=1),
Total=(select count(*) from tb)

西普实验吧CTF-算术题

2016-03-29 18:38:59

又一道简单题

2016-08-23 16:50:12

又一道简单题 CSU - 1785

2017-08-09 18:46:42

csu 1785: 又一道简单题 (没错，简单题）

2017-04-27 12:49:54

一道sql题

2006-11-23 12:58:00

每天一道编程题(1)

2015-09-24 10:15:22

一道小学数学题，坑死我了!!!

2014-10-01 19:35:21

一道真正的数据库sql面试题

2010年05月16日 3KB 下载

Python解一道题的N种做法(1)

2016-02-28 23:46:33

面试中遇到的一道算法题，请各位对我的算法指点一下

2017-12-20 13:49:38