2012-05-27 56 views
1

我有一张桌子关闭以下模型。如何在最后4行数据上执行聚合函数?

public class WeeklyNums 
{ 
    public int FranchiseId { get; set; } 
    public DateTime WeekEnding { get; set; } 
    public decimal Sales { get; set; } 
} 

我需要第四列来计算本周和前三周的最小值。所以输出看起来像这样。

1 7-Jan $1 
1 14-Jan $2 
1 21-Jan $3 
1 28-Jan $4 **1** 
1 4-Feb $4 **2** 
1 11-Feb $6 **3** 
1 18-Feb $4 **4** 
1 25-Feb $8 **4** 
1 3-Mar $7 **4** 

我不知道从哪里开始。即使一些帮助解决它在SQL中会有所帮助。

thx!

+0

你如何定义 “本周”?你用什么日历规则来定义你的星期?或者你只是想要数据库中的最新值,即使它们不是在这一周? –

+0

3月3日的最后记录是不是最小值是4而不是6? –

+0

哪个'SQL Server'版本? – Quassnoi

回答

1

我知道我太晚了,但这里的LINQ版本:

var result = from w1 in db.Table 
      from w2 in db.Table.Where(x => x.WeekEnding >= w1.WeekEnding.AddDays(-28)) 
      select new 
      { 
       FranchiseId = w1.FranchiseId, 
       WeekEnding = w1.WeekEnding, 
       Sales = w1.Sales, 
       SalesMin = w2.Min(x => x.Sales) 
      }; 
3

考虑使用outer apply

select yt1.* 
,  hist.four_week_min 
from YourTable yt1 
outer apply 
     (
     select min(col1) as four_week_min 
     from YourTable yt2 
     where yt2.dt between dateadd(wk, -3, yt1.dt) and yt1.dt 
     ) hist 

SQL Fiddle工作的例子。

+0

不错!我现在将在linqpad中尝试一下。 – DanielEli

+0

我不认为Linq2Sql支持'apply'。 –

+0

sql小提琴?!?!你摇滚!现在尝试转换它linq ... – DanielEli

2
var runningMins = from weekNum in data 
        select new 
           { 
            FranchiseId = weekNum.FranchiseId, 
            WeekEnding = weekNum.WeekEnding, 
            Sales = weekNum.Sales, 
            LastThreeWeeks = data.OrderByDescending(x => x.WeekEnding) 
             .Where(x => x.WeekEnding <= weekNum.WeekEnding) 
             .Take(4) 
             .Min(x => x.Sales) 
           }; 

SQL查询将返回当前与前三次的最低不管日期是否准确3周除了:

With RnkItems As 
    (
    Select DateVal, Sales 
     , Row_Number() Over (Order By DateVal) As Rnk 
    From SourceData 
    ) 
Select * 
    , (
    Select Min(Sales) 
    From RnkItems As R1 
    Where R1.Rnk Between R.Rnk - 3 And R.Rnk 
    ) 
From RnkItems R 
Order By 1 

SQL Fiddle version

相关问题