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

182人阅读 评论(0)

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)

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：394次
• 积分：11
• 等级：
• 排名：千里之外
• 原创：1篇
• 转载：0篇
• 译文：0篇
• 评论：0条
文章存档
评论排行