2010-04-05 50 views
1

我對SQL很陌生。 我有一個基於道路/里程數記錄的數據庫。我的目標是在道路上每52.8英尺獲得一個平均值。我的相關表格每15英尺有一個數據,當然這個表格有一個與主表相關的外鍵。基於距離的SQL平均數據

如果我想按照給定的里程碑每52.8英尺取出一次平均值,我該如何去做呢?

實施例的數據:

 
    RecID Begin_MP End_MP 

    100 0 0.56 

    RecID MP Value1 Value2 
    100  0 159  127.7 
    100 0.003 95.3  115.3 
    100 0.006 82.3  107 
    100 0.009 56.5  74.5 
    100 0.011 58.1  89.1 
    100 0.014 95.2  78.8 
    100 0.017 108.9 242.5 
    100 0.02 71.8  73.3 
    100 0.023 84.1  80.2 
    100 0.026 65.5  66.1 
    100 0.028 122  135.8 
    100 0.031 99.9  230.7 
    100 0.034 95.7  111.5 
    100 0.037 127.3  74.3 
    100 0.04 140.7 543.1 

第一數據是一道道的例子。數據的第二子集的值我需要查詢每52.8英尺

謝謝

+0

我不能完全肯定,我理解的問題。你需要內插嗎?您能否給我們提供您期望獲得的示例數據的輸出結果? – 2010-04-05 20:57:27

+0

什麼味道和版本的SQL? MySQL的? SQL Server?甲骨文? – Thomas 2010-04-05 21:31:16

+0

MySQL很好。我不需要內插,只是52.8以下的任何東西的平均值,以及52.8和105.6之間的任何值。等等.. – jsmith 2010-04-05 21:35:26

回答

2

你可以組52.8英尺塊中的數據。一種方法是將距離除以52.8,然後將其整數。這樣,25屬於組1,100屬於組2,110屬於組3,依此類推。

在SQL Server中,你會寫這樣的:

select 
    52.8 * cast(dist/52.8 as int) as Distance 
, avg(value1) 
, avg(value2) 
from YourTable 
group by cast(dist/52.8 as int) 

下面是與您的數據的例子。由於數據從0至0.04,我將它計算出每0.01英尺塊平均值:

declare @Road table (RecID int, Begin_MP float, End_MP float) 
insert into @Road select 100, 0, 0.56 

declare @Values table (RecID int, MP float, Value1 float, Value2 float) 
insert into @Values values 
(100, 0 , 159 , 127.7), 
(100, 0.003, 95.3 , 115.3), 
(100, 0.006, 82.3 , 107), 
(100, 0.009, 56.5 , 74.5), 
(100, 0.011, 58.1 , 89.1), 
(100, 0.014, 95.2 , 78.8), 
(100, 0.017, 108.9, 242.5), 
(100, 0.02 , 71.8 , 73.3), 
(100, 0.023, 84.1 , 80.2), 
(100, 0.026, 65.5 , 66.1), 
(100, 0.028, 122 , 135.8), 
(100, 0.031, 99.9 , 230.7), 
(100, 0.034, 95.7 , 111.5), 
(100, 0.037, 127.3, 74.3), 
(100, 0.04 , 140.7, 543.1); 

select  
    r.RecID 
, cast(v.MP/0.01 as int)*0.01 as StartMP 
, AVG(v.Value1) as AvgVal1 
, AVG(v.Value2) as AvgVal2 
from  @Road as r 
left join @Values as v 
on  r.RecID = v.RecID 
group by r.RecID, cast(v.MP/0.01 as int) 

此打印:

RecID StartMP AvgVal1 AvgVal2 
100 0.00 98,275 106,125 
100 0.01 87,4  136,8 
100 0.02 85,85 88,85 
100 0.03 107,63 138,83 
100 0.04 140,7 543,1