我有一个应用程序,最终用户可以通过选择一个或多个来运行报告:
- 顾客
- 时间段
- 指标
由于我的应用程序/报告平台的限制,我必须返回一个查询,其中包含用户选择的每个组合的一行,即使该组合没有数据也是如此。
我想看看是否有任何方法可以优化查询,因为我发现将我正在构建的矩阵加入实际财务数据以构建数据集需要花费很多时间回来。
我整理了一个如下示例(SQL Server 2008 R2):
--Average 12 metrics, max 50
declare @Metrics table (MetricID int)
insert into @Metrics values (1000)
insert into @Metrics values (2000)
insert into @Metrics values (3000)
--Average 12 periods, max 24
declare @Periods table (PeriodID int)
insert into @Periods values (201301)
insert into @Periods values (201302)
insert into @Periods values (201303)
--Between 200 and 500 customers
declare @Customers table (CustomerID int)
insert into @Customers values (1)
insert into @Customers values (2)
insert into @Customers values (3)
--Create combined table
declare @IDMatrix table (CustomerID int, PeriodID int, MetricID int)
INSERT INTO @IDMatrix
SELECT x1.CustomerID,
x1.PeriodID,
m.MetricID
FROM (SELECT c.CustomerID, p.PeriodID
FROM @Customers c, @Periods p) x1, @Metrics m
ORDER BY x1.customerid, x1.periodid, m.MetricID
declare @Financials table (CustomerID int, MetricID int, PeriodID int, Value float)
insert into @Financials values (1,1000,201301,984.2)
insert into @Financials values (1,1000,201302,245.1)
insert into @Financials values (1,1000,201303,789.1)
SELECT
i.CustomerID,
i.PeriodID,
i.MetricID,
sum(isnull(f.Value,0))
FROM @IDMatrix i
LEFT JOIN @Financials f ON i.CustomerID = f.CustomerID and i.MetricID = f.MetricID and i.PeriodID = f.PeriodID
GROUP BY
i.CustomerID,
i.PeriodID,
i.MetricID