SQL Server中的查询优化

时间:2018-07-26 09:11:32

标签: sql-server performance optimization sql-server-2014

以下代码需要很长时间才能执行。考虑到每个表都有近5000万到1亿行,我可以在查询方面做些什么来优化它,它是一个源表,每小时涉及大量数据移动(插入数百万次),效果更好没有索引。我没有从此服务器获取执行计划所需的访问权限。

 DECLARE @var INT

 SELECT TOP 1 @var = s_type
 FROM s_shot
 WHERE s_type < 10000
 ORDER BY s_type DESC;

 WITH cte AS
 (
     SELECT 
         sps_id,
         SUM(xin) xin,
         SUM(xout) xout
     FROM 
         s_lock
     GROUP BY 
         sps_id
)
SELECT 
    A.[s_id], a.acc_id,
    B.[o_type],
    B.[o_id], B.[sec_id], B.[c_id],
    B.[style_type_id], [s_type],
    A.[end_date],
    B.[mv], 
    b.xin + ISNULL(c.xin, 0) [xin],
    b.xout + ISNULL(c.[xout], 0) xout,
    b.accr_in + b.accr_inter [acc],
    b.accr_in, b.accr_inter, 
    b.units
FROM 
    s_shot a WITH (NOLOCK)
JOIN 
    s_pos3 b WITH (NOLOCK) ON a.s_id = b.s_id
JOIN 
    cte c ON b.sps_id = c.sps_id
WHERE 
    b.is_sl = 1
    AND a.end_date > DATEADD(mm, -24, GETDATE())  -- 24 months

如您所见,我想获取过去24个月的数据。该查询是否有可能进行优化,以将其执行时间降低到可管理的水平。

下面提供了创建表脚本。

CREATE TABLE [dbo].[s_shot]
(
    [s_id] [int] IDENTITY(1,1) NOT NULL,
    [acc_id] [int] NULL,
    [s_type] [int] NULL,
    [end_date] [datetime] NULL,
    [recon] [tinyint] NULL,
    [is_pers] [tinyint] NOT NULL,
CONSTRAINT [PK_s_shot_1] PRIMARY KEY NONCLUSTERED 
(
    [s_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


CREATE TABLE [dbo].[s_lock]
(
    [sps_id] [int] NOT NULL,
    [units] [decimal](18, 5) NULL,
    [accr_in] [decimal](18, 2) NULL,
    [xin] [decimal](18, 2) NULL,
    [xout] [decimal](18, 2) NULL,
    [lock_date] [date] NOT NULL,
    [accr_inter] [decimal](18, 2) NULL,
    [mv] [decimal](18, 2) NULL,
 CONSTRAINT [PK_s_lock] PRIMARY KEY CLUSTERED 
(
    [sps_id] ASC,
    [lock_date] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[s_pos3]
(
    [sps_id] [int] IDENTITY(1,1) NOT NULL,
    [s_id] [int] NOT NULL,
    [o_type] [tinyint] NOT NULL,
    [o_id] [int] NOT NULL,
    [s_id] [int] NOT NULL,
    [c_id] [int] NOT NULL,
    [s_type_id] [int] NOT NULL,
    [units] [decimal](18, 5) NULL,
    [accr_income] [decimal](18, 2) NULL,
    [distr] [decimal](18, 2) NULL,
    [mv] [decimal](18, 2) NULL,
    [perf_stat] [smallint] NULL,
    [is_slv] [bit] NULL,
    [accr_inter] [decimal](18, 2) NULL,
    [perf_mtd] [decimal](18, 10) NULL,
    [xin] [decimal](18, 2) NULL,
    [xout] [decimal](18, 2) NULL,
    [a_s_type_id] [int] NULL,
 CONSTRAINT [PK_s_pos3] PRIMARY KEY NONCLUSTERED 
(
    [sps_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, 
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

感谢您的帮助。

编辑:更新了索引详细信息

0 个答案:

没有答案