将多个月的记录拆分为各个月

x33g5p2x  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(373)

我在表格中有这样的数据格式-其中日期范围是多月:

  1. SourceSink Class ShadowPrice Round Period StartDate EndDate
  2. AEC Peak 447.038 3 WIN2020 2020-12-01 2021-02-28

我想创建一个视图/插入到一个新表中-上面的记录按月份划分,如下所示:

  1. SourceSink Class ShadowPrice Round Period StartDate EndDate
  2. AEC Peak 447.038 3 WIN2020 2020-12-01 2021-12-31
  3. AEC Peak 447.038 3 WIN2020 2021-01-01 2021-01-31
  4. AEC Peak 447.038 3 WIN2020 2021-02-01 2021-02-28

请告知。

llycmphe

llycmphe1#

只是另一个选择使用 CROSS APPLY 还有一个特别的理货台
例子

  1. Select A.[SourceSink]
  2. ,A.[Class]
  3. ,A.[ShadowPrice]
  4. ,A.[Round]
  5. ,A.[Period]
  6. ,B.[StartDate]
  7. ,B.[EndDate]
  8. From YourTable A
  9. Cross Apply (
  10. Select StartDate=min(D)
  11. ,EndDate =max(D)
  12. From (
  13. Select Top (DateDiff(DAY,[StartDate],[EndDate])+1)
  14. D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),[StartDate])
  15. From master..spt_values n1,master..spt_values n2
  16. ) B1
  17. Group By Year(D),Month(D)
  18. ) B

退货

展开查看全部
jxct1oxe

jxct1oxe2#

一个选项是递归查询。假设周期总是从一个月的第一天开始,到一个月的最后一天结束,如示例数据所示,这将是:

  1. with cte as (
  2. select t.*, startDate newStartDate, eomonth(startDate) newEndDate
  3. from mytable t
  4. union all
  5. select
  6. sourceSink,
  7. class,
  8. shadowPrice,
  9. period,
  10. startDate,
  11. endDate,
  12. dateadd(month, 1, newStartDate),
  13. eomonth(dateadd(month, 1, newStartDate))
  14. from cte
  15. where newStartDate < endDate
  16. )
  17. select * from cte

如果周期开始和结束于不同的月日,那么我们需要更多的逻辑:

  1. with cte as (
  2. select
  3. t.*,
  4. startDate newStartDate,
  5. case when eomonth(startDate) <= endDate then eomonth(startDate) else endDate end newEndDate
  6. from mytable t
  7. union all
  8. select
  9. sourceSink,
  10. class,
  11. shadowPrice,
  12. period,
  13. startDate,
  14. endDate,
  15. dateadd(month, 1, datefromparts(year(newStartDate), month(newStartDate), 1)),
  16. case when eomonth(dateadd(month, 1, datefromparts(year(newStartDate), month(newStartDate), 1))) <= endDate
  17. then eomonth(dateadd(month, 1, datefromparts(year(newStartDate), month(newStartDate), 1)))
  18. else endDate
  19. end
  20. from cte
  21. where datefromparts(year(newStartDate), month(newStartDate), 1) < endDate
  22. )
  23. select * from cte
展开查看全部

相关问题