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

时间:2017-06-23 20:22:39

标签: sql-server-2008 pivot week-number datepart

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

    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       $999    $999    $999
    2       $999    $999    $999
    3       $999    $999    $999

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

我真正想要做的是将每个月分成4周,这样我就可以有48周和34周的时间。每年,像这样:

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

我的最终输出结果如下:

    Month   Week        2015    2016    2017
    ----------------------------------------
    1       1           $999    $999    $999
    1       2           $999    $999    $999
    1       3           $999    $999    $999
    1       4           $999    $999    $999
    2       1           $999    $999    $999
    2       2           $999    $999    $999

我想这样做是因为它对我们来说最具商业意义。

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

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

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

2 个答案:

答案 0 :(得分:0)

如果DAY函数返回当月的日期,您可以使用。

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

答案 1 :(得分:0)

如果你想在 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;
}