2016-06-08 86 views
0

可以幫我優化數據庫此查詢(訪問2010),此查詢工作非常緩慢(如果在一個大表使用它):訪問2010 - 優化查詢

SELECT П1.Code, П1.Field, П1.Number, П1.Data, [П1].[Number]-(select П3.Number from [Table] as П3 
    where П3.Field = П1.Field                
    and П3.Data = (select Max(Data)                   
    from [Table] as П2                   
    where П2.Field = П1.Field and П1.Data > П2.Data)) AS Difference 
FROM [Table] AS П1 
ORDER BY П1.Field, П1.Data; 

我附上圖片:http://s33.postimg.org/otm859xtb/Table_query.png

鏈接數據庫:http://s000.tinyupload.com/?file_id=06711692152703646964

回答

0

......怎麼

SELECT t.Code,t.Field,t.Number,t.Data,t.Number-tm.LastNumber AS Difference 
FROM [Table] AS t 
INNER JOIN (
    SELECT t.Field,t.Number AS LastNumber 
    FROM [Table] AS t 
    INNER JOIN (
    SELECT Field,MAX(Data) AS MaxData 
    FROM [Table] 
    GROUP BY Field 
    ) AS tm ON tm.Field=t.Field AND tm.MaxData=t.Data 
) AS tm ON tm.Field=t.Field 

子選擇可以給你在Access中格式化的一些問題,但應該工作。

0

請嘗試這一個,只是同樣喜歡凱文))

SELECT Table.Code, Table.Field, Table.Number, Table.Data, [Table].[Number]-[t1].[number] AS Difference 
FROM 
(SELECT Table.Code, Table.Field, Table.Number, Table.Data 
FROM [Table] INNER JOIN 
(SELECT Table.Field, Max(Table.Data) AS MaxOfData 
FROM [Table] GROUP BY Table.Field) AS t2 ON (t2.MaxOfData = Table.Data) AND 
(Table.Field = t2.Field)) AS t1 INNER JOIN [Table] ON t1.Field = Table.Field;