每月检索最大周数减去2

时间:2019-04-24 10:50:57

标签: sql sql-server tsql

我正在尝试检索每个月的最大周数减去2,从今年至今的周数减去2。

Sample data

January    Feb
Week 1     Week 5
Week 2     Week 6
Week 3     Week 7
Week 4     Week 8

输出:

January    Feb
Week 1     Week 1
Week 2     Week 2
           Week 3
           Week 4
           Week 5
           Week 6

因此,对于Jan,最大周数是第4周,因此我们需要第1周和第2周。

2月,最大周数是第8周,因此我们将第1周到第6周作为第6周的8-2。

模式如下:

Date (daily)
Year
Month
Week

Example
Date           Year      Month      Week
05/01/2019     2019      January    1

希望这有意义吗?

谢谢!

afk

1 个答案:

答案 0 :(得分:0)

我省略了日期,因为您的Week编号可能有所不同,但是原理是相同的,如果您的源数据中已经有Week编号。您所需要做的就是通过max找到Week Month个数字,然后使用一个自join返回同一年中所有Week值,且值较小值:

declare @t table([Year] int,[Month] varchar(15),[Week] int);
insert into @t values(2019,'January',1),(2019,'January',2),(2019,'January',4),(2019,'February',5),(2019,'February',6),(2019,'February',7),(2019,'February',8),(2019,'March',9),(2019,'March',10),(2019,'March',11),(2019,'March',12),(2019,'March',13);

with m as
(
    select [Year]
          ,[Month]
          ,max([Week])-2 as MaxWeek
    from @t
    group by [Year]
            ,[Month]
)
select m.[Year]
      ,m.[Month]
      ,t.[Week]
from @t as t
    join m
        on t.[Year] = m.[Year]
            and t.[Week] <= m.MaxWeek
order by m.[Year]
        ,m.[Month]    -- Replacing this with your actual date value should give you correct sorting
        ,t.[Week];

输出

+------+----------+------+
| Year |  Month   | Week |
+------+----------+------+
| 2019 | February |    1 |
| 2019 | February |    2 |
| 2019 | February |    4 |
| 2019 | February |    5 |
| 2019 | February |    6 |
| 2019 | January  |    1 |
| 2019 | January  |    2 |
| 2019 | March    |    1 |
| 2019 | March    |    2 |
| 2019 | March    |    4 |
| 2019 | March    |    5 |
| 2019 | March    |    6 |
| 2019 | March    |    7 |
| 2019 | March    |    8 |
| 2019 | March    |    9 |
| 2019 | March    |   10 |
| 2019 | March    |   11 |
+------+----------+------+