The query is executing very slowly, is there any way to improve it any further?

后端 未结 8 1111
长情又很酷
长情又很酷 2021-02-15 17:26

I have the following query, and because of a lot of SUM function calls, my query is running too slow. I have a lot of records in my database and I would like to get

8条回答
  •  情书的邮戳
    2021-02-15 17:47

    I would use a lookup table "Dates" table to join my data to with an index on DatesId. I use the dates as a filter when I want to browse historical data. The join is fast and so it the filtering as the DatesId is clustered primary index (primary key). Add the date column (as included column) for your data table as well.

    The dates table has the following columns:

    DatesId, Date, Year, Quarter, YearQuarter, MonthNum, MonthNameShort, YearWeek, WeekNum, DayOfYear, DayOfMonth, DayNumOfWeek, DayName

    Example data: 20310409 2031-04-09 2031 2 2031-Q2 4 April Apr 2031_15 15 99 9 3 Wednesday

    You can PM me if you want a csv of this so that you can import it to the database, but I'm sure you can easily find something like this online and make your own.

    I add an identity column as well so that you can get an integer for each date. This makes it a bit easier to work with, but not a requirement.

    SELECT * FROM dbo.dates where dateIndex BETWEEN (getDateIndexDate(getDate())-30 AND getDateIndexDate(getDate())+0) --30 days ago
    

    This allows me to easily jump back to a certain period. It's quite easy to create your own views on this. You can of course use the ROW_NUMBER() function to do this for years, weeks, etc. as well.

    Once I have the daterange I want, I join to the data. Works very fast!

提交回复
热议问题