SQL Server : get data where date + last 2 financial years - sql

I wish to find data from where current date and also include data from the last 2 financial years
Basically I want data going back from 'today' to 01/04/2019. I want to add this line of data to dynamically happen, not just a one off for the future
Thus if the date today was 05/06/2022, I would want the date going from that date, backwards until what would be 01/04/2020
The column name is Date - please help

I am quite sure that it should be possible to do it in some simpler way, but you can use something like below:
declare #b date
set #b = datefromparts(year(getdate()),4,1) --first daty of fiscal year in current calendar year
select case when #b<getdate() then dateadd(year,-2,#b) else dateadd(year,-3,#b) end

Related

how to automate the date change in a query using transact sql

I work for a company where everyday I modify a query by changing the date of the day before, because the report is always from the previous day.
I want to automate the date change. I have made a table with two columns, one with all dates from this year and another with bits where if 0 is a working day and 1 if is a holiday.
I have successfully automated a little bit by telling if the day before is a working day then subtract 1 from the date (This is what happens everyday). But the problem is, that if is Monday appears as Friday, because Saturday and Sunday are not billable. And let's also say, that if today is Thursday and Wednesday and Tuesday we're holidays, then the report will run on Monday. I will leave you a picture, that shows how the table is made with dates.
Remembering, that if there is no holidays in the middle of the week, always will be subtract one.
The way to do this sort of thing is close to what you have done, but just extend it further. Create a BusinessDate table that has every date, and then every rule you have implemented inside it. You can go so far as to include a column such as ReportDate which will return,for every date, what date the report should be run for.
Do this once, and it will work forever more. You may have to update for future holidays once a year, but better than once a day!
It will also allow you to update things specific for your business, like quarter dates, company holidays, etc.
If you want to know more on the subject, look up topics around creating a date dimension in a data warehouse. Its the same general issue you are facing.
Too complicated for a comment and it involves a lot of guessing.
So everyday, your process starts by first determining if "today" is a work day. So you would do something like:
if exists (select * from <calendar> where date = cast (getdate() as date) and IsWorkday = 1")
begin
<do stuff>
end;
The "do stuff" section would then run a report or your query (or something that isn't very clear) using the most recent work day prior to the current date. You find that date using something like:
declare #targetdate date;
set #targetdate = (select max(date) from <calendar>
where date < cast (getdate() as date)
and IsWorkday = 1);
if #targetdate is not null
<run your query using #targetdate>
That can be condensed into less code but it is easier to understand when the logic is written step-by-step.

Get the month and year now then count the number of rows that are older then 12 months in SQL/Classic ASP

I know this one is pretty easy but I've always had a nightmare when it comes to comparing dates in SQL please can someone help me out with this, thanks.
I need to get the month and year of now then compare it to a date stored in a DB.
Time Format in the DB:
2015-08-17 11:10:14.000
I need to compare the month and year with now and if its > 12 months old I will increment a count. I just need the number of rows where this argument is true.
I assume you have a datetime field.
You can use the DATEDIFF function, which takes the kind of "crossed boundaries", the start date and the end date.
Your boundary is the month because you are only interested in year and month, not days, so you can use the month macro.
Your start time is the value stored in the table's row.
Your end time is now. You can get system time selecting SYSDATETIME function.
So, assuming your table is called mtable and the datetime object is stored in its date field, you simply have to query:
SELECT COUNT(*) FROM mtable where DATEDIFF(month, mtable.date, (SELECT SYSDATETIME())) > 12

Changing the year of a date in SQL

I am relatively new to programming. I have a table and in the table I have a column which shows when an employee started at the company. I am creating a procedure and within that procedure, I want to take the users start date and replace it with the current year, this will then be followed by an if statement. If the date that has just been calculated is before today, then change the year of the date to next year. Thanks and sorry if the question isn't fully clear or has been asked before.
I don't think this is the most elegant solution, but you could take the date apart to replace it with the current year. Then use a case statement to change it to the next year if it has already passed. Here's the code:
SELECT employee_name,
CASE
WHEN CONVERT(VARCHAR,MONTH(start_date))+'/'+CONVERT(VARCHAR,DAY(start_date))+'/'+CONVERT(VARCHAR,YEAR(getdate())) < GETDATE() THEN CONVERT(VARCHAR,MONTH(start_date))+'/'+CONVERT(VARCHAR,DAY(start_date))+'/'+CONVERT(VARCHAR,YEAR(getdate())+1)
WHEN CONVERT(VARCHAR,MONTH(start_date))+'/'+CONVERT(VARCHAR,DAY(start_date))+'/'+CONVERT(VARCHAR,YEAR(getdate())) >= GETDATE() THEN CONVERT(VARCHAR,MONTH(start_date))+'/'+CONVERT(VARCHAR,DAY(start_date))+'/'+CONVERT(VARCHAR,YEAR(getdate()))
END AS anniversary_date
FROM Employees

How to get month within a range vb2010

I just don't know how to go about this.
I designed a program that uses MS Access as its database. I have a field for month and year (the field data type is text) where user can register details. The program will register the month and year the user have chosen e.g month= September, year=2011.
My problem now is how to chose a range of data to view by the user using the month and year as a criteria e.g the User may want to view data range from (September 2011 to July 2013).
I couldn't figure out even how to try. Help will be highly appreciated.
Perhaps you could change your application logic to store the month and year as their respective numbers rather than text and change the field data types to numeric.
You could then construct a DateTime object from them, for example September would be 9 and you could use code like the following:
var startDate = new DateTime(year, month, 1); // get year and month as integers from database, uses the first as the date
var endDate = new DateTime(year, month, 10); // change the date but keeps the month and year the same
var endDate2 = startDate.AddMonths(1); // adds 1 month to the date
Alternatively, you could try using a calendar control to allow the user to select two dates instead of building it from a number of fields. Depending on what you are using this could be achieved a number of ways, for example in ASP.Net or WPF you could use two calendar controls and just use their SelectedDate properties as your range.
A range is from a startpoint until an end point. For the startpoint you can add automatically the first of Month. For the endpoint is it more complicated because there is no fix endpoint. What you can do is following:
Write an array that contains for each month the days (e.g. 30 or 31). Except for Febrauary there is a fix pattern.
for Febrauary use the selected year to check is the year a leap year or not. If not add 28, else add 29.
After that create the date string for your SQL:
Startdate 1.9.2011. Do for the entdate the same.
After that, I think you can use the keyword between in your SQL query.
You can assume that everything is entered on the first day of each month. I would pull the information using a query to the database.
select * from [tablename] where DateSerial([colYear], [colMonth], 1) between DateSerial([fromYear], [fromMonth], 1) and DateSerial([toYear], [toMonth], 1)
In this question are some ways to do this:
First. Filter the dates in a range assuming that you use a date like '07-12-2012'
i.e. September 2011 to July 2013
Where DateColumn > '09-01-2011' and DateColumn < '07-31-2013'
OR
Specify a Date and a Year
Where month(DateColumn)='1' and year(DateColumn)='2016'
Note:
There are many ways to do this.
You can Manipulate your statement depending on your desired output.

SQL Stored Procedure: Business Hours

How can I create a stored procedure that accepts a start and end date.(e.g April 1 - April 30
1.) Get the business days including Saturdays x (a value). +
2.) Get Holidays x (a value)
and return the total.
I'm new to this, I guess it would be a tsql function. hmm.
any help would be appreciated.
Thanks
The simplest solution to this problem is to create a Calendar table that contains a value for every day you might want to consider. You could then add columns that indicate whether it is a business day or a holiday. With that, the problem becomes trivial:
Select ..
From Calendar
Where IsBusinessDay = 1
And Calendar.[Date] Between '2010-04-01' And '2010-04-30'
If you wanted the count of days, you could then do:
Select Sum( Case When IsBusinessDay = 1 Then 1 Else 0 End ) As BusinessDayCount
, Sum( Case When IsHoliday = 1 Then 1 Else 0 End ) As HolidayCount
From Calendar
Where Calendar.[Date] Between '2010-04-01' And '2010-04-30'
http://classicasp.aspfaq.com/date-time-routines-manipulation/how-do-i-count-the-number-of-business-days-between-two-dates.html
First, you will need to store all of the holidays into an independant table (Christmas, Easter, New Year Day, etc. with their respective dates (normally timed at midnight));
Second, you will have to generate, into a temporary table maybe, the dates of the office days, it then excludes the dates contained in the Holidays table.
Third, you may set the office hours to these dates depending on what day it is, if you have different working hours on different day.
That is the algorithm for you to find the appropriate code implementation.
Let me know if this helps!