以下查询返回正确的结果,但如何更快地获得相同的结果?
目标是通过汇总他们今天、本周、本月和季度的销售额来输出一个用于跟踪卖家进度的表格。
SellerID Today ThisWeek ThisMonth ThisQuarter
----------- --------------------- --------------------- --------------------- ---------------------
1 400,00 700,00 900,00 900,00
2 950,00 1850,00 2650,00 2650,00
我的查询:
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] >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()),0) THEN [Price] END) AS Today,
SUM(CASE WHEN [Date] >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0) THEN [Price] END) AS ThisWeek,
SUM(CASE WHEN [Date] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) THEN [Price] END) AS ThisMonth,
SUM(CASE WHEN [Date] >= DATEADD(QUARTER, DATEDIFF(QUARTER, 0, GETDATE()), 0) THEN [Price] END) AS ThisQuarter
FROM #sales
WHERE DATEPART(YEAR, [Date]) = DATEPART(YEAR, GETDATE())
GROUP BY SellerID
在更大的表上执行相同的查询时,这会变得很慢。仅删除 CASE 语句即可将执行时间缩短近 50%。
我怎样才能以更快、更有效的方式获得相同的结果?