MSSQL - 如何将每个月分成 4 周?

MSSQL - How to divide each month into 4 weeks?

我有一个接近满足我需要的查询:

    select  *
    from
    (
    select      DATEPART (YEAR, order_date) as theYear,
                DATEPART (WEEK, order_date) as theWeek,
                SUM (order_totalPrice) as totalSales
    from        orders_tbl
    where       order_date >= '01/01/2015'
    group by    DATEPART (YEAR, order_date), DATEPART (WEEK, order_date)
    ) as mySourceTable
    pivot
    (
        sum (totalSales)
        for theYear in ([2015], [2016], [2017])
    ) as myPivotTable
    order by theWeek asc

结果如下:

    Week    2015    2016    2017
    ----------------------------
    1       9    9    9
    2       9    9    9
    3       9    9    9

但这将 "weeks" 定义为从一周中的某一天开始的 7 天。 (我认为星期一是默认值)。

我真正想做的是把每个月分成 4 周,这样我每年就有 48 "weeks",像这样:

    Day of Month    Week #
    -----------------------
    1-7             1
    8-14            2
    15-21           3
    22+             4

我的最终输出如下:

    Month   Week        2015    2016    2017
    ----------------------------------------
    1       1           9    9    9
    1       2           9    9    9
    1       3           9    9    9
    1       4           9    9    9
    2       1           9    9    9
    2       2           9    9    9

我想这样做,因为这对我们来说最有商业意义。

如何修改上述查询以实现此目的?

规定 1:这是我从 Web 应用程序代码中调用的查询(所以,我认为这排除了一些 T-SQL 的东西......对吧?)是的,我可以使用Web 应用程序代码执行各种循环或其他操作,但有没有办法完全在单个 SQL 查询中执行此操作?

规定2:我用的是MS SQL 2008 R2.

如果 DAY 函数是 returns 一个月中的某一天,您就可以使用它。

DAY(order_date) AS DayOfMonth

接下来您可以构建自己的逻辑,例如:

CASE WHEN DAY(order_date) >= 1 AND DAY(order_date) < 8 THEN 1 
WHEN DAY(order_date) >= 8 AND DAY(order_date) < 15 THEN 2
WHEN DAY(order_date) >= 15 AND DAY(order_date) < 22 THEN 3
ELSE 4 END AS WeekNumber

如果您想在 Laravel 中将月分成周,以下代码可能对您有所帮助

public function weeksOfMonth($year = null, $month)
{
    if($year == null ):
        $year = Carbon::now()->year;
    endif;
    $date = Carbon::createFromDate($year,$month);
    $j=1;
    $week_array = [];
    for ($i=1; $i <= $date->daysInMonth ; $i++) {
        Carbon::createFromDate($year,$month,$i); 
        $start_date = Carbon::createFromDate($year,$month,$i)->startOfWeek()->toDateString();
        $end_date = Carbon::createFromDate($year,$month,$i)->endOfweek()->toDateString();
        $week_array[$j]['start_date'] = $start_date;
        $week_array[$j]['end_date'] = $end_date;
        $week_array[$j]['week'] = 'week'.$j;
        $i+=7;
        $j++; 
    }
    return $week_array;
}