2011-03-02 138 views
1

我有一個數據庫表,有一個日期字段,一個用戶名字段和一個整數點平衡字段。每天都有記錄,在工作日結束時存儲餘額。Sql平均每天增加

我正在尋找最有效的方法來計算每個用戶的平均每日增加量,並將最高平均每日增加量排序到最低。

enter image description here

+0

您是否有單獨的表格,其中包含所有用戶名?平均每個用戶有多少條記錄? – 2011-03-02 19:58:20

回答

0

假設平衡總是增加,你可以只找到第一天的餘額,在最後一天的平衡,並計算平均值(根據天#):

;with minmax as (-- subquery to get min/max data per user 
    select 
     username 
     ,min(capturedate) as mincapturedate 
     ,min(balance) as minbalance 
     ,max(capturedate) as maxcapturedate 
     ,max(balance) as maxbalance 
    from 
     [5171722] t 
    group by username 
) 
,averageincrease as (-- subquery to calculate average daily increase 
    select 
     username 
     ,datediff(day, mincapturedate, maxcapturedate) as numdays 
     ,(maxbalance - minbalance) as totalincrease 
     ,(maxbalance - minbalance)/datediff(day, mincapturedate, maxcapturedate) as 
      averagedailyincrease 
    from 
     minmax 
) 
-- pull results together, with highest average daily increase first 
select 
    * 
from 
    averageincrease 
order by 
    averagedailyincrease desc 

字段averagedailyincrease最後包含平均每日增加量。

+0

我認爲這是最好的一般想法,但不喜歡假設平衡總是會增加,'min(date)'將與'min(balance)'等於同一行等等。 – 2011-03-02 19:57:26

+0

@Martin:我同意。但是,如果這些假設由OP進行審查,它會更有效率。 – mellamokb 2011-03-02 20:04:08

2

這應該適用於MS SQL Server。它假定每個用戶每個日期確實有一個條目,日期間沒有空白,並且不會隨時間(小時,分鐘,秒)值出現。 (另外,沒有空值!)它會計算每日平均增加量,無論它是否實際上每天增加。

SELECT mt.UserName, avg(mt.Balance - mt2.Balance) AvgDailyIncrease 
from MyTable mt 
    inner join MyTable mt2 
    on mt2.UserName = mt.UserName 
    and mt2.CaptureDate = dateadd(dd, -1, mt.CaptureDate) 
group by mt.UserName 
order by avg(mt.Balance - mt2.Balance) desc 
+0

+1,但也許更準確地計算實際平均值(即將int轉換爲float)。輸出平均值仍可能使用四捨五入的「int」值。 – 2011-03-02 22:43:22