Sql server 使用SQL Server 2012改进查询的性能?

Sql server 使用SQL Server 2012改进查询的性能?,sql-server,performance,sql-server-2008,sql-server-2012,database-tuning,Sql Server,Performance,Sql Server 2008,Sql Server 2012,Database Tuning,我有一个表,它有130000条记录,但没有索引,我写了一个查询,它有4个左外部联接 查询工作正常,没有任何问题。我唯一关心的是性能,给出结果需要5-10分钟。所以我的问题是如何提高查询的性能?我的第二个问题是我是否需要添加索引?如果是,我应该添加哪个索引,集群索引还是非集群索引 我的问题是: 在我看来,通过使用条件聚合,您可以一次性解决整个查询 我没有太多地使用SQL Server,所以我不太了解日期逻辑,但据我所知,您正在计算不同时间段的金额,比如年初以来的累计金额、月初以来的累计金额以及今天

我有一个表,它有130000条记录,但没有索引,我写了一个查询,它有4个左外部联接

查询工作正常,没有任何问题。我唯一关心的是性能,给出结果需要5-10分钟。所以我的问题是如何提高查询的性能?我的第二个问题是我是否需要添加索引?如果是,我应该添加哪个索引,集群索引还是非集群索引

我的问题是:


在我看来,通过使用条件聚合,您可以一次性解决整个查询

我没有太多地使用SQL Server,所以我不太了解日期逻辑,但据我所知,您正在计算不同时间段的金额,比如年初以来的累计金额、月初以来的累计金额以及今天的金额等等

对于这样的查询,您无论如何都要处理BillDate介于年初和今天日期之间的所有记录。您应该能够使用类似于下面的查询。其思想是仅当BillDate在时间段内时才对金额求和

select a.SpecialisationCode
      ,a.Specialisation
      ,sum(case when a.BillDate = today then a.Amount1 end) as Amount1_Today
      ,sum(case when a.BillDate between date 'first-day-in-month' and today then a.Amount1 end) as Amount1_MTD
      ,sum(a.Amount1) as Amount1_YTD
  from tbl_doctor
 where a.SpecialisationCode!=0
   and a.Specialisation NOT IN (' ')   
   and a.BillDate between date 'first day in year'
                      and date 'today'
 group 
    by a.SpecialisationCode
      ,a.Specialisation;
如果你不让它工作,请告诉我

select a.SpecialisationCode
      ,a.Specialisation
      ,sum(case when a.BillDate = today then a.Amount1 end) as Amount1_Today
      ,sum(case when a.BillDate between date 'first-day-in-month' and today then a.Amount1 end) as Amount1_MTD
      ,sum(a.Amount1) as Amount1_YTD
  from tbl_doctor
 where a.SpecialisationCode!=0
   and a.Specialisation NOT IN (' ')   
   and a.BillDate between date 'first day in year'
                      and date 'today'
 group 
    by a.SpecialisationCode
      ,a.Specialisation;