Note that there are some explanatory texts on larger screens.

plurals
  1. POFastest way of summarizing sales based on today, this week, this month, this quarter this year?
    primarykey
    data
    text
    <p>The following query returns a correct result but how do I get the same result faster? </p> <p>The goal is to output a table for tracking sellers progress by summarizing their sales today, this week, month and quarter.</p> <pre><code>SellerID Today ThisWeek ThisMonth ThisQuarter ----------- --------------------- --------------------- --------------------- --------------------- 1 400,00 700,00 900,00 900,00 2 950,00 1850,00 2650,00 2650,00 </code></pre> <p>My query:</p> <pre><code>CREATE TABLE #sales( [Price] MONEY, [Date] DATE, [SellerID] INT ) INSERT INTO #sales VALUES (100, '2012-01-01', 1), (200, '2012-04-01',1), (300, '2012-04-23',1), (400, '2012-04-27',1), (700, '2012-01-01', 2), (700, '2012-01-02', 2), (800, '2012-04-01',2), (900, '2012-04-23',2), (950, '2012-04-27',2) SELECT SellerID AS SellerID, SUM(CASE WHEN [Date] &gt;= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()),0) THEN [Price] END) AS Today, SUM(CASE WHEN [Date] &gt;= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0) THEN [Price] END) AS ThisWeek, SUM(CASE WHEN [Date] &gt;= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) THEN [Price] END) AS ThisMonth, SUM(CASE WHEN [Date] &gt;= DATEADD(QUARTER, DATEDIFF(QUARTER, 0, GETDATE()), 0) THEN [Price] END) AS ThisQuarter FROM #sales WHERE DATEPART(YEAR, [Date]) = DATEPART(YEAR, GETDATE()) GROUP BY SellerID </code></pre> <p>When executing the same query on a larger table this gets quite slow. Just removing the CASE-statements cuts the execution time by almost 50%.</p> <p>How can I achieve the same result in a faster and more efficient way?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload