Create calendar table in SQL Server

会有一股神秘感。 提交于 2020-07-23 07:35:15

问题


I am using Microsoft SQL Server 2012 and I am creating the following table:

Clinic_code Clinic_name        D        D_days_passed
------------------------------------------------------
   A123       NAME1       2018-12-01         1      
   A124       NAME2       2018-12-01         1      
   A125       NAME3       2018-12-01         1      
   [...]
   A123       NAME1       2018-12-02         2      
   A124       NAME2       2018-12-02         2      
   A125       NAME3       2018-12-02         2      
   [...]
   A123       NAME1       2018-12-03         3      
   A124       NAME2       2018-12-03         3     
   A125       NAME3       2018-12-03         3   

I adapted the code here from @JohnCappelletti, but I'm struggling to include the 'D_days_passed' column which essentially counts the number of days since the Start_date:

DECLARE @fromdate date = '2018-12-01'

SELECT #MyTable.*, B.D
FROM #MyTable
CROSS APPLY
    (SELECT TOP (DATEDIFF(DAY, @fromdate, DATEADD(Month, 9, @fromdate)) + 1) 
         D = CONVERT(date, DATEADD(DAY, -1 + ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), @fromdate))
     FROM master..spt_values n1) B

If you have time,

Question: how could the code be adjusted to, instead of including every day from one date to another per Clinic, I wanted to introduce the same week period per clinic, such as this, from Saturday-Sunday:

Clinic_code Clinic_name        D_start        D_end         Weeks_passed
-------------------------------------------------------------------------
   A123       NAME1           2018-12-02   2018-12-08             1      
   A124       NAME2           2018-12-02   2018-12-08             1      
   A125       NAME3           2018-12-02   2018-12-08             1      
   [...]
   A123       NAME1           2018-12-09   2018-12-15             2 
   A124       NAME2           2018-12-09   2018-12-15             2 
   A125       NAME3           2018-12-09   2018-12-15             2 
   [...]
   A123       NAME1           2018-12-16   2018-12-22             3
   A124       NAME2           2018-12-16   2018-12-22             3
   A125       NAME3           2018-12-16   2018-12-22             3

回答1:


You can just use window functions to get the earliest date and then datediff():

Select t.*, B.D,
       datediff(day, min(date) over (), date) + 1 as days_passed
From  #MyTable t Cross Apply
      (Select Top (DateDiff(DAY,@fromdate,DateAdd(Month,9,@fromdate))+1) 
                  D=convert(date,DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),@fromdate))
       From  master..spt_values n1
      ) B;

This should also work for weeks.



来源:https://stackoverflow.com/questions/62837665/create-calendar-table-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!