Sql server sqlserver查询优化
我的问题是,我创建的查询执行时间太长Sql server sqlserver查询优化,sql-server,performance,Sql Server,Performance,我的问题是,我创建的查询执行时间太长 City | Department | Employee | Attendance Date | Attendance Status ------------------------------------------------------------------------ C1 | Dept 1 | Emp 1 | 2016-01-01 | ABSENT C1 | Dept 1 |
City | Department | Employee | Attendance Date | Attendance Status
------------------------------------------------------------------------
C1 | Dept 1 | Emp 1 | 2016-01-01 | ABSENT
C1 | Dept 1 | Emp 2 | 2016-01-01 | LATE
C1 | Dept 2 | Emp 3 | 2016-01-01 | VACANCY
因此,我想创建一个包含相同数据的视图,并添加一个包含员工总数的列(该列稍后在SSRS项目中用于确定每个状态的百分比)
因此,我创建了一个函数,可以根据部门和日期进行简单的选择过滤
这是使用函数的查询:
SELECT City, Department, Employee, [Attendence Date], [Attendance Status], [Get Department Employees By Date](Department, [Attendence Date]) AS TOTAL
FROM attendenceTable
CREATE FUNCTION [dbo].[Get Department Employees By Date]
(
@deptID int = null,
@date datetime = null
)
RETURNS nvarchar(max)
AS
BEGIN
declare @result int = 0;
select @result = count(*) from attendenceTable where DEPT_ID = @deptID and ATT_DATE_G = @date;
RETURN @result;
END
这就是功能:
SELECT City, Department, Employee, [Attendence Date], [Attendance Status], [Get Department Employees By Date](Department, [Attendence Date]) AS TOTAL
FROM attendenceTable
CREATE FUNCTION [dbo].[Get Department Employees By Date]
(
@deptID int = null,
@date datetime = null
)
RETURNS nvarchar(max)
AS
BEGIN
declare @result int = 0;
select @result = count(*) from attendenceTable where DEPT_ID = @deptID and ATT_DATE_G = @date;
RETURN @result;
END
问题是查询执行时间太长(我的意思是很长)。
有什么优化建议吗?您的函数是一个标量函数,对结果集中的每一行运行一次(~600000)次,是已知的性能杀手。可以将其重写为一个内联表值函数,或者如果其他地方不需要该逻辑,则一个简单的组count&join就足够了:
WITH EmployeesPerDeptPerDate
AS ( SELECT DEPT_ID ,
ATT_DATE_G ,
COUNT(DISTINCT Employee) AS EmployeeCount
FROM attendenceTable
GROUP BY DEPT_ID ,
ATT_DATE_G
)
SELECT A.City ,
A.Department ,
A.Employee ,
A.[Attendence Date] ,
A.[Attendance Status] ,
ISNULL(B.EmployeeCount, 0) AS EmployeeCount
FROM attendenceTable AS A
LEFT OUTER JOIN EmployeesPerDeptPerDate AS B ON A.DEPT_ID = B.DEPT_ID
AND A.ATT_DATE_G = B.ATT_DATE_G;
那个表中有什么索引?您通常如何过滤这些数据?请同时包括功能代码。数据经常变化吗?这能超过高峰之夜吗?数据库是MS SQL吗?你有索引吗?我只是想运行它以便继续我的工作,我等了将近一个半小时(该表有593236条记录)。@Garethleyons编辑后包含的代码:)