1

我有一张以下型号的桌子。

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 中解决它的一些帮助也会有所帮助。

谢谢!

4

3 回答 3

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的工作示例。

于 2012-05-27T19:42:20.573 回答
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 查询将返回当前和前三个中的最小值,无论日期是否恰好相隔三周:

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 小提琴版本

于 2012-05-27T20:10:57.087 回答
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)
             };
于 2012-05-27T19:56:11.660 回答