Sql server 获取聚合日期统计信息/数据透视的最快方法
我试图写一份相当普通的审计报告;一段时间内添加到表中的行数;对照以前的周期进行报告,以了解数据的趋势 我有一个表,用于审核数据库中行的创建。它有一个字段ROWENTEREDATE date time。我希望每周/每月/当前季度/年度创建一份审计报告 在我的头脑中,我把它看作是对日期周围数据的多次传递;这在我的数据库中是相当昂贵的。我目前的理由是 我一开始是为我的年/月/季度制定日期Sql server 获取聚合日期统计信息/数据透视的最快方法,sql-server,sql-server-2008,tsql,report,Sql Server,Sql Server 2008,Tsql,Report,我试图写一份相当普通的审计报告;一段时间内添加到表中的行数;对照以前的周期进行报告,以了解数据的趋势 我有一个表,用于审核数据库中行的创建。它有一个字段ROWENTEREDATE date time。我希望每周/每月/当前季度/年度创建一份审计报告 在我的头脑中,我把它看作是对日期周围数据的多次传递;这在我的数据库中是相当昂贵的。我目前的理由是 我一开始是为我的年/月/季度制定日期 set datefirst 1 declare @dateranges table ( rangelab
set datefirst 1
declare @dateranges table (
rangelabel varchar(100),
startdate datetime,
enddate datetime,
myrowcount integer identity(1,1)
)
insert into @dateranges (Rangelabel, startdate, enddate)
select
'Current Year',
DATEADD(yy, DATEDIFF(yy,0,GETDATE()), 0),
DATEADD(ms,-3,DATEADD(yy, DATEDIFF(yy,0,GETDATE() )+1, 0))
insert into @dateranges (Rangelabel, startdate, enddate)
select
'Current Quarter',
DATEADD(qq, DATEDIFF(qq,0,GETDATE()), 0),
DATEADD(qq, DATEDIFF(qq, - 1, getdate()), - 1)
insert into @dateranges (Rangelabel, startdate, enddate)
select
'Current Month',
DATEADD(month, DATEDIFF(month, 0, getdate()), 0),
DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
如果我的表是tblofuselfacts,而我的日期行是RowEnteredDate,那么获取聚合的最佳方式是什么;被白天打破了
Date Range Mon Tues Wed Thu Fri Sat Sun
Year To date 12000 13000 12000 3200 98000 8900 4000
Quarter 1 302 407 201 97 1732 120 37
Month ...
使用这样的查询,我可以很容易地得到每天的总数
select
count(*) ,
datepart(weekday, RowEnteredDate)
from
tblOfUsefullFacts aa
Where
datepart(weekday, RowEnteredDate) is not null
group by datepart(weekday, RowEnteredDate)
order by datepart(weekday, RowEnteredDate) sac
这将逐行选择数据输出;我可以通过旋转和循环来获取数据。我有点紧张,因为实际数字在百万分之十,如果我能避免的话,我不想影响基本的处理
由于我需要在多个过程中执行此操作,是否有一种更轻松的方法来执行此操作,而无需运行循环来获取总数?或者我的模糊大脑忽略了SQL中的一个机制。这应该给你一个方法。很抱歉出现语法错误,它未经测试
;with cte as
(
select
d.rangelabel,
datepart(weekday, RowEnteredDate) as WkDay,
count(*) as RowCt
from tblOfUsefullFacts f
join @dateranges d on f.RowEnteredDate between d.startdate and d.enddate
Where datepart(weekday, RowEnteredDate) is not null
group by d.rangelabel,datepart(weekday, RowEnteredDate)
)
select
RangeLabel,
sum(case when WkDay = 1 then RowCt else 0 end) as Sunday,
sum(case when WkDay = 2 then RowCt else 0 end) as Monday,
sum(case when WkDay = 3 then RowCt else 0 end) as Tuesday,
sum(case when WkDay = 4 then RowCt else 0 end) as Wednesday,
sum(case when WkDay = 5 then RowCt else 0 end) as Thursday,
sum(case when WkDay = 6 then RowCt else 0 end) as Friday,
sum(case when WkDay = 7 then RowCt else 0 end) as Saturday
from cte
group by RangeLabel
根据我今天早上的测试;获得信息和最终支点肯定比三次传球快。谢谢:)