Advertisement
Pandaaaa906

Untitled

Aug 28th, 2023
1,255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.25 KB | None | 0 0
  1. with mid_records as (
  2. -- 加入row_number(),按prj_id分组,按raw_records.date 正序排序
  3.     select records.*,
  4.     row_number() over(partition by prj_id order by raw_records.date asc) prj_r  -- spoil alert: 出问题的地方
  5.     from raw_records
  6. ), records as (
  7. -- 加入last_date
  8.     select mid_records.*, cast(null as datetime2) last_date
  9.     from mid_records
  10.     where mid_records.prj_r = 1
  11.  
  12. union all
  13.  
  14.     select
  15.     mid_records.*,
  16.     case when datepart(year, last_record.date) = datepart(year, raw_records.date) and datepart(month, last_record.date) = datepart(month, raw_records.date) then last_record.last_date  -- 如果上一条是同一个月的,用上一条的last_date
  17.     else last_record.date end last_date
  18.     from records last_record
  19.     join mid_records
  20.     on last_record.prj_id = raw_records.prj_id
  21.     AND last_record.prj_r + 1 = raw_records.prj_r
  22. )
  23.  
  24. select
  25. records.*,
  26. mat_summary.sum_value
  27.  
  28. from records
  29.  
  30. outter apply(
  31. select
  32. sum(value)
  33. from mat
  34. where mat.prj_id = records.prj_id
  35. and mat.date < last_second_of_month(records.date)  -- 取records.date当月以及之前未重复关联的mat进行汇总
  36. and (records.last_date is null or mat.date > first_date_of_month(records.last_date))  
  37. ) mat_summary
  38.  
  39.  
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement