2013-04-08 22 views
0

我有當最終用戶可以通過選擇一個或多個運行報告的應用程序:的SQL Server:提高交叉的效率加入到創建矩陣結果

  • 客戶
  • 時間週期
  • 指標

由於我的應用程序/報表平臺中存在約束,因此即使沒有該組合的數據,我也必須返回包含用戶選擇的每個組合的一行的查詢。

我想看看是否有任何方法可以優化查詢,因爲我發現需要相當多的時間才能加入矩陣我構建到實際財務數據以構建數據集將被返回。

我已經把一個樣品(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 
+0

查詢的期望結果是什麼? – Taryn 2013-04-08 17:36:14

+0

@bluefeet - 期望的結果是按照最後的選擇語句。如果存在財務數據表中的財務數據,則需要每個客戶/期間/指標組合的記錄 – Tom 2013-04-08 17:38:30

+3

請使用交叉聯接語法而不是隱式語法。對於一個正在調整這個意義的人來說,這將更加明顯。 – HLGEM 2013-04-08 18:17:00

回答

1

我會建議您嘗試使用臨時表,而不是對矩陣表變量,然後編入索引。