问题描述如下:
有一个Web访问量记录的表T_WebPV,建表及初始化数据语句如下:
CREATE TABLE T_WebPV ( ID INT PRIMARY KEY IDENTITY(1, 1) , --主键 RecordTime VARCHAR(10) , --记录时间 PV INT ,--访问量 ChapterID INT --文章ID ); GO INSERT INTO dbo.T_WebPV ( RecordTime, PV, ChapterID ) VALUES ( '2016-01-16', -- RecordTime - varchar(10) 2000, -- PV - int 1 -- ChapterID - int ); INSERT INTO dbo.T_WebPV ( RecordTime, PV, ChapterID ) VALUES ( '2016-01-17', -- RecordTime - varchar(10) 2200, -- PV - int 1 -- ChapterID - int ); INSERT INTO dbo.T_WebPV ( RecordTime, PV, ChapterID ) VALUES ( '2016-01-16', -- RecordTime - varchar(10) 2600, -- PV - int 2 -- ChapterID - int ); INSERT INTO dbo.T_WebPV ( RecordTime, PV, ChapterID ) VALUES ( '2016-01-17', -- RecordTime - varchar(10) 2300, -- PV - int 2 -- ChapterID - int );
现需根据某天来统计本天、本周及本月的PV访问量。例如要统计2016-01-17及该周、该月的PV访问量(可忽略周、月的时间段计算),希望得到的结果如下:
select a.ChapterID,a.DayPV,b.WeekPV,c.MonthPV from ( select ChapterID,sum(pv) as DayPV from T_WebPV t where t.RecordTime='2016-01-17' group by t.ChapterID) a, ( select ChapterID,sum(pv) as WeekPV from T_WebPV t where t.RecordTime BETWEEN 周开始日期 and 周结束日期 group by t.ChapterID )b, ( select ChapterID,sum(pv) as MonthPV from T_WebPV t where t.RecordTime BETWEEN 月开始日期 and 月结束日期 group by t.ChapterID ) c where a.ChapterID=b.ChapterID and a.ChapterID=c.ChapterID