Convert Month to Range of Dates

Hi All,
I need help it writing a T-SQL which converts a single month into the all the dates of that month.
I tried and tried, and  nothing came to my brain. I need from experts like you.
Table Data
P_Status
Month Daily Prod
Unit
Jan-14 1
4
Feb-14 3
6
The output needs to be like this 
Month Daily Prod
Unit
1/1/2014 1
4
1/2/2014 1
4
1/31/2014 1
4
2/1/2014 3
6
2/2/2014 3
6
2/28/2014 
3 6
Thanks in advance.

if you can't (or don't want to) create a calendar table (you should, its super helpful) then you could use this function instead:
create function Dates(@date datetime)
returns @table table
now datetime,
today datetime,
Month_start datetime,
Month_end datetime,
Prev_Month_Start datetime,
Prev_Month_End datetime,
Week_Start datetime,
Week_End datetime,
Prev_Week_Start datetime,
Prev_Week_End datetime,
Quarter_Start datetime,
Quarter_End datetime,
Prev_Quarter_Start datetime,
Prev_Quarter_End datetime,
Year_Start datetime,
Year_End datetime,
Prev_Year_Start datetime,
Prev_Year_End datetime,
Month_End_TS datetime,
Prev_Month_End_TS datetime,
Week_End_TS datetime,
Prev_Week_End_TS datetime,
Quarter_End_TS datetime,
Prev_Quarter_End_TS datetime,
Year_End_TS datetime,
Prev_Year_End_TS datetime,
Year smallint,
Month smallint,
Day smallint,
Month_Name varchar(15),
Day_Name varchar(15),
WD smallint
as
begin
if @date IS NULL set @date = getdate()
insert into @table
select
@date as now,
convert(datetime,convert(varchar,@date,101)) as today,
dateadd(day,0-day(@date)+1,convert(datetime,convert(varchar,@date,101))) as Month_Start,
dateadd(day,-1,dateadd(month,1,dateadd(day,0-day(@date)+1,convert(datetime,convert(varchar,@date,101))))) as Month_end,
dateadd(month,-1,dateadd(day,0-day(@date)+1,convert(datetime,convert(varchar,@date,101)))) as Prev_Month_start,
dateadd(day,-1-day(@date)+1,convert(datetime,convert(varchar,@date,101))) as Prev_Month_End,
dateadd(day,1-datepart(dw,@date),convert(datetime,convert(varchar,@date,101))) as Week_Start,
dateadd(day,7-datepart(dw,@date),convert(datetime,convert(varchar,@date,101))) as Week_End,
dateadd(day,-6-datepart(dw,@date),convert(datetime,convert(varchar,@date,101))) as Prev_Week_Start,
dateadd(day,0-datepart(dw,@date),convert(datetime,convert(varchar,@date,101))) as Prev_Week_End,
convert(datetime,convert(varchar,year(@date)) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,@date)-1)*3)+1),2)+'-01') as quarter_start,
dateadd(day,-1,dateadd(quarter,1,convert(datetime,convert(varchar,year(@date)) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,@date)-1)*3)+1),2)+'-01'))) as quarter_end,
convert(datetime,convert(varchar,year(dateadd(quarter,-1,@date))) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,dateadd(quarter,-1,@date))-1)*3)+1),2)+'-01') as prev_quarter_start,
dateadd(day,-1,dateadd(quarter,1,convert(datetime,convert(varchar,year(dateadd(quarter,-1,@date))) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,dateadd(quarter,-1,@date))-1)*3)+1),2)+'-01'))) as prev_quarter_end,
dateadd(day,1-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101))) as Year_Start,
dateadd(year,1,dateadd(day,0-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101)))) as Year_End,
dateadd(year,-1,dateadd(day,1-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101)))) as Prev_Year_Start,
dateadd(year,-1,dateadd(year,1,dateadd(day,0-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101))))) as Prev_Year_End,
dateadd(ms,-3,dateadd(day,0,dateadd(month,1,dateadd(day,0-day(@date)+1,convert(datetime,convert(varchar,@date,101)))))) as Month_End_Ts,
dateadd(ms,-3,dateadd(day,-1-day(@date)+2,convert(datetime,convert(varchar,@date,101)))) as Prev_Month_End_TS,
dateadd(ms,-3,dateadd(day,8-datepart(dw,@date),convert(datetime,convert(varchar,@date,101)))) as Week_End_TS,
dateadd(ms,-3,dateadd(day,1-datepart(dw,@date),convert(datetime,convert(varchar,@date,101)))) as Prev_Week_End_TS,
dateadd(ms,-3,dateadd(day,0,dateadd(quarter,1,convert(datetime,convert(varchar,year(@date)) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,@date)-1)*3)+1),2)+'-01')))) as quarter_end_TS,
dateadd(ms,-3,dateadd(day,0,dateadd(quarter,1,convert(datetime,convert(varchar,year(dateadd(quarter,-1,@date))) +'-'+ right('0'+convert(varchar,((datepart(QUARTER,dateadd(quarter,-1,@date))-1)*3)+1),2)+'-01')))) as prev_quarter_end_TS,
dateadd(ms,-3,dateadd(year,1,dateadd(day,1-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101))))) as Year_End_TS,
dateadd(ms,-3,dateadd(day,1-day(@date),dateadd(month,1-month(@date),convert(varchar,@date,101)))) as Prev_Year_End_TS,
Year(@date) as Year,
Month(@date) as Month,
Day(@Date) as Day,
datename(month,@Date) as Month_Name,
datename(WEEKDAY,@date) as Day_Name,
datepart(weekday,@date) as WD
return
end
go
select * from dbo.Dates(getdate())
go
drop function dbo.dates

Similar Messages

  • How to select Months with in a date range

    Hi
    I am working on a report which will list out Month wise totals in each row.
    How should i select the Months with in a date range and do the sum ( User may select the date range for  N number of  years also. Example :  01/10/2000 to 01/01/2010 )
    Thanks in advance
    Thanks&regards
    Mrudula

    Hi
       Use the following code:
    data: l_date(8) value '03042007',
            l_mname   type   t247-ktx,
            l_c(25).
      select single ktx from t247
      into l_mname
      where spras = sy-langu
      and mnr = l_date+2(2).
      concatenate l_mname l_date+6(2)
      into l_c." SEPARATED BY space.
      data: g_date(10) type c. " Processing date of Report
      g_date = sy-datum.
      concatenate g_date0(4)  g_date4(2)  g_date+6(2) into g_date.
      data: g_date1(10) type c.
      g_date1 = so_verab-high.
      concatenate g_date10(4)  g_date14(2)  g_date1+6(2) into g_date1.
    Regards,
    Sreeram

  • Date Control should highlight more than one range of dates in a month.

    Hi All,
    Date Control should highlight more than one range of dates in a month.We are creating a web interface for PR01 ( Travel Management Module ) , in a month a traveller can have more than 2 trips and we need to highlight all the travel date ranges in the Web DynPro date range control.
    Thanks & Regards
    Gaurav Jain

    Hi Thomas,
       I used DateNavigatorLegend and DateNavigatorMarking and did not give any default value or context mapping to the DateNavigator element.
      The DateNavigator is now highlighting only the first dates of the ranges that I have created in the WDDOINIT method.The DateNavigatorMarking takes only one date not 2 dates in the properties So kindly suggest how to display multiple date ranges.
    Thanks & Regards
    Gaurav Jain

  • How to break range of dates into different months in mm/yyyy format

    See the following eg:
    MaterialNo         Validfrom         ValidTo            RecordNo                    Value
    A100                01.01.2007        13.05.2007       1000                           1150/-
                             14.05.2007       24.08.2007        1001                           1550/-
    Now I want to break these dates into mm/yyyy format based on a condition. If the date(day) 15th lies in the range of dates
    then it should pick that Value.
    The output should be in this format.
    MaterialNo         Validfrom         ValidTo                    Date                         RecordNo                    Value
    A100                01.01.2007        13.05.2007            012007                            1000                           1150/-
                                                                                    022007                            1000                           1150/-
                                                                                    032007                            1000                           1150/-
                                                                                    042007                            1000                           1150/-
    A100               14.05.2007       24.08.2007            052007                               1001                           1550/-
                                                                                    062007                               1001                           1550/-
                                                                                    072007                               1001                           1550/-
                                                                                    082007                               1001                           1550/-

    Hi Shiva,
    In your Report Program, you can define the field of type sy-datum. And then fill the fields with the date. And then you can extract the rest of it manually by this small and simple lines of code. Once you have the date extracting logic then you can output the date in any manner according to your wish.
    data : lv_date  TYPE sy-datum.
    data : lv_month TYPE c LENGTH 2.
    data : lv_year  TYPE c LENGTH 4.
    data : lv_month_year TYPE c LENGTH 6.
    lv_date = sy-datum.
    lv_month = lv_date+4(2).
    lv_year  = lv_date+0(4).
    CONCATENATE lv_month lv_year INTO lv_month_year.
    Hope this helps.
    Thanks,
    Samantak.

  • Converting varchar to datetime where date field is missing

    Hello Sir,
    i have a column with varchar datatype values like '2013/12','2012/11' where date field is missing.  i want to convert it as datetime at runtime so that i can use datetime related function. Is it possible for ms sql server 2008?
    thanking you.

    >> I have a column with VARCHAR data type values like '2013/12', '2012/11' where DATE field is missing. I want to convert it as DATETIME2(0) at runtime so that I can use DATETIME2(0) related function. Is it possible for MS SQL Server 2008? <<
    The most important leg on a three-legged stool is the leg that is missing :)  A DATE is made up of three fields; YEAR, MONTH and DAY. You gave no business rule for picking the DAY field, so this makes no sense. 
    Since SQL is a database language, we prefer to do look ups and not calculations. They can be optimized while temporal math messes up optimization. A useful idiom is a report period calendar that everyone uses so there is no way to get disagreements in the DML.
    The report period table gives a name to a range of dates that is common to the entire enterprise. 
    CREATE TABLE Something_Report_Periods
    (something_report_name CHAR(10) NOT NULL PRIMARY KEY
      CHECK (something_report_name LIKE <pattern>),
     something_report_start_date DATE NOT NULL,
     something_report_end_date DATE NOT NULL,
     CONSTRAINT date_ordering
      CHECK (something_report_start_date <= something_report_end_date),
    etc);
    These report periods can overlap or have gaps. I like the MySQL convention of using double zeroes for months and years, That is 'yyyy-mm-00' for a month within a year and 'yyyy-00-00' for the whole year. The advantages are that it will sort with the ISO-8601
    data format required by Standard SQL and it is language independent. The pattern for validation is '[12][0-9][0-9][0-9]-00-00' and '[12][0-9][0-9][0-9]-[01][0-9]-00' in the CHECK constraints. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Function module which convert number to days to date

    Hi,
    Any one knows any function module which convert total number of days into date.
    thnaks,
    shilpa k

    Hi,
        FIMA_DAYS_AND_MONTHS_AND_YEARS
    FI_PSO_DAYS_MONTHS_YEARS_GET
    RSSM_CONVERT_DAYSEC2TIMESTAMP
    RSSM_CONVERT_TIMESTAMP2DAYSEC
    Function Modules related to Date and Time Calculations
    DATE_COMPUTE_DAY : Returns weekday for a date
    DATE_GET_WEEK : Returns week for a date
    DAY_ATTRIBUTES_GET : Returns attributes for a range of dates specified
    MONTHS_BETWEEN_TWO_DATES : To get the number of months between the two dates.
    END_OF_MONTH_DETERMINE_2 : Determines the End of a Month.
    HR_HK_DIFF_BT_2_DATES : Find the difference between two dates in years, months and days.
    FIMA_DAYS_AND_MONTHS_AND_YEARS : Find the difference between two dates in years, months and days.
    MONTH_NAMES_GET : Get the names of the month
    WEEK_GET_FIRST_DAY : Get the first day of the week
    HRGPBS_HESA_DATE_FORMAT : Format the date in dd/mm/yyyy format
    SD_CALC_DURATION_FROM_DATETIME : Find the difference between two date/time and report the difference in hours
    L_MC_TIME_DIFFERENCE : Find the time difference between two date/time
    HR_99S_INTERVAL_BETWEEN_DATES : Difference between two dates in days, weeks, months
    LAST_DAY_OF_MONTHS : Returns the last day of the month
    Regards

  • Discrete time range over date range  (using CR X1)

    Post Author: sjr
    CA Forum: Formula
    Can anyone show me how to select data over a discrete time range i.e. 6 p.m. till 11 p.m. per day, over a period of a month ?
    Using the data time parameter gives me data from 6p.m. on startdate right through till 11p.m. on endate.

    Here's a more detailed description...
    Create two formula fields to split the date and time from the data records (ds prefixed):
    dsDate
    dsTime
    Create two formula fields to split the date and time from the parameter fields (pm prefixed):
    pmStartDate
    pmStartTime
    pmStartDate
    pmStartTime
    Use your new formula fields in the record selector. Get to this off the Report menu button (in CR 2008):
    Report | Select Expert... | Record.
    You can pick the formula fields in the Forumula Editor to create something like:
    ({@dsDate} > {@pmStartDate} and
    {@dsDate} < {@pmEndDate}) and
    ({@dsTime} > {@pmStartTime} and
    {@dsTime} < {@pmEndTime)
    Tim

  • Formula mode (Returns the most repetitive  value in range of data)

    Hi all,
    I'm using XIR2.0 but in the next month we will use R3, does anybody knows if the mode (Returns the most frequently occurring, or repetitive, value in an array or range of data. ) formula exist in this new version?
    Thanks.

    Hi all,
      The formula exists in WEBI is MODE, this formula doesn't exists in DESKI.
    Thanks.

  • Extract Range of Data / Waveform Zoom

    I have an NRF recording file with several channels. What I need to do is visualize the data and then extract a small part of the waveforms into a TDM or Matlab file. I actually managed to get all this done in DIAdem, but in a most cumbersome way:
    1) Import NRF file into the Data Portal using the DataPlugin
    2) Convert all signal channels to Waveform channels (using the function in the ANALYSIS module)
    3) Display the waveforms in the VIEW module
    4) Zoom downto the sample level in order to figure out where to start and stop the extraction
    5) Write down the start/stop x-coordinates (i.e. XStart, XEnd)
    6) Switch to the ANALYSIS module and generate a numeric channel with "First value" = Xstart, "Last value" = XEnd and "No. of values" = (XEnd - XStart)/SampleTime
    7) Use "Linear Mapping..." to extract the desired data
    8) Convert the extracted data to a waveform channel
    9) Export data to desired file format
    Now for my questions:
    * I'm using DIAdem 10.0 (Base Edition) and would like to know if there is not a much simpler way of getting this job done, i.e. selecting two points on a waveform, click one button and get the data between those points as a new waveform in the Data Portal (ideally for several waveforms in parallel)
    * Isn't there any way of zooming out one step in the waveform viewer? I only found zoom on/off which is a rather crude way for navigating)
    * Are there any news regarding the topic in the thread "Selecting a range of data from a file" (last posts date back to February 2005)
    Any help is greatly appreciated. Thanks

    Hi,
    * How can I run a VBS script with my Base Edition: the whole Script feature is disabled, but I was under the impression that I can run scripts (just not edit/debug)
    ... with an Link on the Desktop from your DIAdem. In Properties of this Link, you can set the Parameter:
    "DIAdem.exe" "/cScriptStart('MyScript')"
    ... with the start Script in every Module in DIAdem. Have a look at the Screenshot.
    * Isn't there any way of zooming out one step in the waveform viewer? I only found zoom on/off which is a rather crude way for navigating
    ... I´m sorry Zoom out isn´t anywhere! But you can make it like the second picture. With the upper Graph, you an control what you see in the second Graph. Zoom In/Out, no Problem
    * Also how can I precisely (down to the sample level) place the two band cursors? Using the different zoom modes I manage to do it for one of the two cursors, but not the other one.
    Sorry, I don´t understand your question! Perhaps you can precisely set you Cursor with the Coordinat Window? Have a look!
    Best regards
    Alex
    Attachments:
    Start Script.gif ‏6 KB
    Zoom.gif ‏55 KB

  • Convert Safari History lastvisiteddate to date time

    I want to Convert Safari History lastvisiteddate to date time.

    Post Author: newcruser
    CA Forum: Crystal Reports
    Thanks
    This is easy...second group based on the second formula 'for each hour'.
    How you group by 15 minutes?.
    i want to group by every 15 minutes starting from 9 AM to 5 PM.
    First i need to create a time range and then use that time range to group?.  Or any other simple and best way to solve this?. Please help
    How to create time range from 9 AM to 5 PM?

  • Convert month to numbers

    Hi,
    I want to convert month to numbers and I don t want to write a long if-else for it!
    It has to be a smarter way to solve this.
    Does anybody know how to do that?
    I already get the month from a site and if it�s Oct, then I want to show it as a 10. I have searched in Date classes but it didn t help.
    Nini

    I get the date with RSS news and I would like to
    convert it to another format.
    Ninijava.text.SimpleDateFormat is your answer.
    :D

  • How to get period date of for a given month from a given date in mdx for SSRS report (mm/dd/yyyy)

    I have a situation,  where i need to write expression Period to date(PTD). i want to know how to get the period date. i want you to help in writing Period date or else is there any function to get period date for a given date(the  date is given
    from the parameter dynamically) in MDX for SSRS report
    ram

    Hi ram,
    Per my understanding that you want to get the period date based on the month selected and the given date, right?
    Could you please provide details information below to help us better understanding your requirements, thus we will be more effective to provide an solution:
    What is the format of the period date you want to get, is this date in the DB and you want to filter it based on the month and the given Date?
    Did the month and given date are two parameters in the report? if possible, could you please provide some sample data in the DB and also the snapshot of the report structure
    I assume you want to get the period date(mm/dd/yyy) between the select month(e.g:Feb) and the given date (10/1/2014) and you should get the date between(02/01/2014-10/1/2014).
    If so,and you also have two parameter "Month","EndDate"(EndDate is the given date), please reference to details information below:
    You can create an new parameter "BeginDate" (Date/Time) which is the begin date of the period, you can use the expression to get the value based on the value of the month and the year value from the given date,finally hide this parameter:
    Specify the available value:
    Label:=Parameters!Month.Value &"/01/"& DatePart("yyyy",Parameters!EndDate.Value)
    Value:=CDate(=Parameters!Month.Value &"/01/"& DatePart("yyyy",Parameters!EndDate.Value))
    Specify the default Value:
    Value:=CDate(=Parameters!Month.Value &"/01/"& DatePart("yyyy",Parameters!EndDate.Value))
    Add filter to the dataset as below:
    Preview you will get all the date in the given Period:
    If you still have any problem, please feel free to ask.
    Regards
    Vicky Liu

  • How to calculate the month difference between two date char. in Query?

    Customers would like to see how many months passed between two date type of characteristics (e.g., the month difference between the current date and the scheduled delivery date in the record) and put the result into the column as KF. 
    We would have to grab the fiscal year/period kind of value and then do the subtraction, e.g., if the current date value is 2/28/2008 and the scheduled delivery date value in the record is 12/01/2007, the correct result should be 2 month difference between these two date values, but could someone here give us the technical light on how to make this happen in query design?
    Thanks and we will give you reward points for the correct anwsers!

    Hi Kevin,
    The Badi is RSR_OLAP_BADI.
    You can create an implementation using Transaction  SE18.
    The implementation is per cube and is defined in the filters.
    In the Implementation you have the following methods :
    1. Define : Here you will provide the Keyfigure you need as a virtual one.
    2. Initilialize : Any Init Function you want to do.
    3. Compute. This is called per datarecord and here you can cimpute your value.
    Hope this helps.
    Pralay Ahluwalia

  • Month end accrual posting date- Last day of the month

    Hi Experts,
    I have set up month end accruals for PY US by configuring posting dates, LDCD, WageType accrual processing class, Schema changes. I have also set the closing dates as the end of the month.
    Now after I do the posting , there are three documents getting generated.
    1. Accrual posting document with first day of the current month
    2. Normal Payroll posting  document with payroll period posting date
    3. Accrual reversal document with first day of the following month.
    My Question is:  As per standard SAP configuration, the month end accrual will have first day of the month. Can we customize this to end of the month for doc#1 - accrual document?
    Please do let me know your suggestion and ideas.
    Thanks,
    Amosha

    Hello,
    I have a similar question and I hope to have more details on how to change the posting date.
    The point is that I have an amount of 1200 and I have to post 100 for each month.
    Key Date for Accruals: 31.01.2011
    I posted 100 with Document date: 31.01.2011 and Posting date 31.01.2011
    Key Date for Accruals: 28.01.2011
    I posted 200 with Document date: 28.02.2011 and Posting date 28.02.2011
    Also I reversed the amount posted in the previous month (100) with Document date: 31.01.2011 Posting date 28.02.2011
    And so on...
    The problem are the dates because I need to post the amount at the end of each month (28/02) and to reverse the previous amount at the beginning of the next month (01/02).
    How can I change these dates?
    Thanks a lot in advance
    Kind Regards,
    E.

  • How to load a range of data in Diadem?

    Hello; I have a set of Access DB containing analytic data of 5 jears. How can I import a range of data (eg. all year 2003 data)in Diadem for analysis?
    Thank's

    Thank's,
    but I couldn't choose explizit the time channel. Also I couldn't set a command like 'between 1.1.2003 and 31.12.2003'. Attached is an exemple of the dataset. The time channel is '50_DAT'.
    It would be nice to get an answer.
    Thank's Matthias
    Attachments:
    B0P2DAT8_50.MDB ‏400 KB

Maybe you are looking for

  • [Kernel] USB and network trouble

    Hey all, i have some trouble getting my system fully running. I have a built in 3com network card, it uses the 3c59x module in the kernel (got it build into the kernel). I also have a usb cd writer. When i start writing my network fails after sometim

  • Mass deletion of open PR & PO

    hai all MM gurus, How to delete the open or pending PR's & PO's which are created on duration of any periods like 1.1.2008 to 31.3.2008?.

  • Keynote 09 files not recognized as "Presentations" by Spotlight

    I have folders with various presentations in Powerpoint, Keynote 08 and Keynote 09 formats. I have setup Smart Folders with search criteria that show me these presentations in a single view. I use the search criteria "Kind = Presentations" to narrow

  • Framemaker's future

    Hi there. I'm a Doc Lead for a large IT company.  I've been tasked w/ finding another tool/software to use for creating and maintaining a large (800 page) document (right now, they use Word, and it can't handle this file, which is basically a user's

  • Workbench freezes on call to BAPI_PRODORDCONF_GETLIST Request/Response XML

    I have created a simple transaction in MII 12.0.6 with three JRA actions: Start Session, Function Call, and End Session.  From the configuration dialog of the Function Call action, I confirmed the existance of BAPI_PRODORDCONF_GETLIST via a BAPI sear