Iterate by increment of parameter - sql

I have Sql query as below example.
Select
number,age
from
tbldetails
where
month = #Month and year = #Year
union
Select
number,age
from
tblcontacts
where
month = #Month and year = #Year
Now I want to get details of above query for past 12 months of #Month and #Year and then do average on age.
Example #Month = Dec and #Year = 2015
I want to get age for Jan 2015 to Dec 2015 and then do average .
I want to use this in ssrs report.
Hoping to get some help :)

To filter for the desired date range, I would combine the year and month into one string column and then use that to compare to your converted parameters (minus one year).
WHERE CAST(YEAR AS VARCHAR(4) + RIGHT('00' + CAST(MONTH AS VARCHAR(2)), 2)
>= CAST((#YEAR - 1) AS VARCHAR(4) + RIGHT('00' + CAST(#MONTH AS VARCHAR(2)), 2)

Declare #Year int;
Set #Year = '2016'
Declare #Month varchar(10);
Set #Month = '11'
Declare #Date varchar(10);
Set #Date = Cast(#Month as varchar(2))+'-'+'01'+'-'+Cast(#year as varchar(4))
Declare #StartDate varchar(19);
Set #StartDate = Convert(varchar(19),DateAdd(m,-12,#Date),103) -- 103 dd/mm/yy
Declare #EndDate varchar(20);
Set #EndDate = Convert(varchar(20),DateAdd(m,12,#StartDate),103)
Select
Sum( StCount) as TotalStudents
(
Select Count(Rollnbr) as StCount,..
Where Date between #StartDate and #EndDate
union
Select Count(Rollnbr) as StCount,..
Where Date between #StartDate and #EndDate
)Sql1

Related

How to get the last day of the month using only month and year?

I want to find out how to find the last day of the month if I only have a year and a month (and no day).
I tried using EOMONTH(), but this function needs the date consisted of year, month and day. I can only use year and month values.
How do I do something like this?
If you are using Sql Server 2012 then I'd use DATEFROMPARTS.
DECLARE #year SMALLINT = 2016
,#month TINYINT= 02
SELECT EOMONTH(DATEFROMPARTS(#year,#month,1))
You can still use EOMONTH even if you do not have a day of the month, just use the first of the month as the day of month is not significant in the input.
-- incoming parameters (assuming string but could be int and you could cast them)
DECLARE #month VARCHAR(2) = '11', #year VARCHAR(4) = '2016'
DECLARE #date DATETIME
DECLARE #lastDayOfMonth INT
SELECT #date = CONVERT(date, #year + #month + '01', 101) -- this first part is what you know (year + month), the 01 is just the first day of whatever month appended so the date is valid
-- get the last day of month as a date using EOMONTH and then use DATEPART to get the day of the month
SELECT #lastDayOfMonth = DATEPART(dd, EOMONTH(#date))
SELECT #lastDayOfMonth -- your output on the screen
VARCHAR TYPES
DECLARE #D DATE
DECLARE #YearV VARCHAR(4) = '2016'
DECLARE #MonthV VARCHAR(2) = '12'
SET #D = DATEADD(dd,-1,DATEADD(mm,1,CAST(#YearV + #MonthV + '01' AS DATE)))
SELECT #D
INT TYPES
DECLARE #D DATE
DECLARE #Year INT = '2016'
DECLARE #Month INT = '11'
SET #D = DATEADD(dd,-1,DATEADD(mm,1,CAST(CAST(#Year AS VARCHAR(4)) + CAST(#Month AS VARCHAR(2)) + '01' AS DATE)))
SELECT #D
COMBINED TYPES
some SUBSTRING code depending on the format... :)

Find Quarter Months Based on Payroll Cycle

This would be in the "where" clause...how do I find quarters based on a payroll cycle? Our payroll cycle starts on the 25th of the quarter month and ends on the 10th of the quarter month. For example...
The 2nd quarter starts on 4/25/2016 and ends on 7/10/2016.
Ok it's kind of hard to understand completely what you are doing but here is something that should work. You can edit the dates to fit what you want but I made it based off what you stated.
--This is just test data... you can use your own table
IF OBJECT_ID('tempdb..#payroll') IS NOT NULL DROP TABLE #payroll
CREATE TABLE #payroll (dates date)
INSERT INTO #payroll (dates) VALUES
('1/1/2016'),
('1/16/2016'),
('2/4/2016'),
('3/3/2016'),
('3/19/2016'),
('4/18/2016'),
('5/6/2016'),
('6/4/2016'),
('6/29/2016'),
('7/4/2016'),
('7/31/2016'),
('8/9/2016'),
('9/1/2016'),
('10/3/2016'),
('10/19/0216'),
('11/4/2016'),
('11/21/2016'),
('12/2/2016'),
('1/1/2016'),
('1/8/2017'),
('1/21/2017')
--variable for what ever quarter you want to limit on. 1-4
declare #Quarter int
set #Quarter = 4
--Year that you are focused on. If left to NULL it uses the current year
declare #Year int
set #Year = NULL
IF #Year IS NULL
BEGIN
SET #Year = Year(GETDATE())
END
--Date parameters that we will use to filter
declare #startDate date = null
declare #endDate date = null
--logic to set your quarters
set #startDate = case
when #Quarter = 1 then '1/25/' + CAST(#Year as varchar(4))
when #Quarter = 2 then '4/25/' + CAST(#Year as varchar(4))
when #Quarter = 3 then '7/25/' + CAST(#Year as varchar(4))
when #Quarter = 4 then '9/25/' + CAST(#Year as varchar(4))
end
set #endDate = case
when #Quarter = 1 then '4/10/' + CAST(#Year as varchar(4))
when #Quarter = 2 then '7/10/' + CAST(#Year as varchar(4))
when #Quarter = 3 then '9/10/' + CAST(#Year as varchar(4))
when #Quarter = 4 then '1/10/' + CAST((#Year + 1)as varchar(4))
end
--run it to test results
select *
from #payroll
where dates between #startDate and #endDate

How to get last date of particular month from the month ID and year in SQL? [duplicate]

This question already has answers here:
Get the last day of the month in SQL
(22 answers)
Closed 7 years ago.
How to get last date of particular month from the month ID and year in SQL ?
Inputs :
#MonthID INT = 2,
#Year INT = 2015
Required output : 28/02/2015
It's easy in SQL Server 2012+
To frame date from the year and month use DATEFROMPARTS (Transact-SQL)
To find the last day of month use EOMONTH (Transact-SQL)
Declare #MonthID INT = 2,
#Year INT = 2015
SELECT Eomonth(Datefromparts(#Year, #MonthID, 1))
For any thing less then Sql server 2012
SELECT Dateadd(dd, -1, Dateadd(mm, 1, Cast(Cast(#Year AS CHAR(4)) + '-'
+ Cast(#MonthID AS VARCHAR(2))+'-'+'1' AS DATE)))
Note: If the variables are of Varchar type then you can remove the cast to varchar
You can find the last day of the month in the following manner
Declare #MonthID varchar(10) = '02', #Year varchar(10) = '2015'
select dateadd(dd,-1,dateadd(MM,1,cast(#Year+'-'+#MonthID+'-1' as date)))
This is how I did it.
DECLARE #MonthID INT = 3,
#Year INT = 2015
DECLARE #InputDate DATE, #TempDate DATE, #OutputDate DATE
SET #InputDate = CAST(CAST(#Year AS VARCHAR) + '-' + CAST(#MonthID AS varchar) + '-01' AS DATE)
SET #TempDate = #InputDate
WHILE (DATEPART(m, #InputDate) = DATEPART(m, #TempDate))
BEGIN
SET #OutputDate = #TempDate
SET #TempDate = DATEADD(d,1,#TempDate)
END
SELECT #OutputDate

SQL Server : setting two variables month and year for previous month, year roll over safe

I'm trying to basically dynamically set two variables (#month and #year) to be whatever the previous month and year were.
So in today's case #month = 7 and #year = 2012
But I want something safe for the year roll around, so if it's 1/1/2013 I would get #month = 12 and #year = 2012.
Thanks!
This is what I have.
declare #month int
declare #year int
set #month = month (getDate ())-1
set #year = 2012
You can use DATEADD to subtract a month from the current date, then grab the MONTH and YEAR portions:
DECLARE #monthAgo dateTime
DECLARE #month int
DECLARE #year int
SET #monthAgo = DATEADD(month, -1, GETDATE())
SET #month = MONTH(#monthAgo)
SET #year = YEAR(#monthAgo)
Shown in steps. You can modify the value assigned to #Now to test.
DECLARE #Now DateTime = GETDATE();
DECLARE #Then DateTime = DATEADD(Month, -1, #Now);
DECLARE #Month Int = DATEPART(Month, #Then);
DECLARE #Year Int = DATEPART(Year, #Then);
SELECT #Month, #Year;
can you not just add, after what you already have:
if #month = 0
begin
set #month = 12
set #year = #year - 1
end
As a single query, this gives the first day of last month:
select DATEADD(month,DATEDIFF(month,'20010101',CURRENT_TIMESTAMP),'20001201')
You can, if you choose, pull that apart into two separate variables, but why bother? (I assume the rest of what you're doing is working with datetimes also, rather than ints)
The two datetime strings above are selected because they have the desired relationship between them - that the second starts 1 month before the first.
Try this
declare #month int
declare #year int
Declare #dt datetime=getdate()
set #month = DATEPART(mm,DATEADD(mm,-1,#dt))
select #month
set #year = DATEPART(yy,DATEADD(mm,-1,#dt))
select #year

SQL: How to produce next date given month and day

In my table I have a Month(tinyint) and a Day(tinyint) field. I would like to have a function that takes this month and day and produces a datetime for the next date(including year) given this month and day.
So if I had Month = 9, Day = 7 it would produce 9/7/2009.
If I had Month 1, Day 1 it would produce 1/1/2010.
something like this would work. It's variation on your method, but it doesn't use the MM/DD/YYYY literal format, and it won't blowup against bad input (for better or for worse).
declare #month tinyint
declare #day tinyint
set #month = 9
set #day = 1
declare #date datetime
-- this could be inlined if desired
set #date = convert(char(4),year(getdate()))+'0101'
set #date = dateadd(month,#month-1,#date)
set #date = dateadd(day,#day-1,#date)
if #date <= getdate()-1
set #date = dateadd(year,1,#date)
select #date
Alternatively, to create a string in YYYYMMDD format:
set #date =
right('0000'+convert(char(4),year(getdate())),4)
+ right('00'+convert(char(2),#month),2)
+ right('00'+convert(char(2),#day),2)
Another method, which avoids literals all together:
declare #month tinyint
declare #day tinyint
set #month = 6
set #day = 24
declare #date datetime
declare #today datetime
-- get todays date, stripping out the hours and minutes
-- and save the value for later
set #date = floor(convert(float,getdate()))
set #today = #date
-- add the appropriate number of months and days
set #date = dateadd(month,#month-month(#date),#date)
set #date = dateadd(day,#day-day(#date),#date)
-- increment year by 1 if necessary
if #date < #today set #date = dateadd(year,1,#date)
select #date
Here is my sql example so far. I don't really like it though...
DECLARE #month tinyint,
#day tinyint,
#date datetime
SET #month = 1
SET #day = 1
-- SET DATE TO DATE WITH CURRENT YEAR
SET #date = CONVERT(datetime, CONVERT(varchar,#month) + '/' + CONVERT(varchar,#day) + '/' + CONVERT(varchar,YEAR(GETDATE())))
-- IF DATE IS BEFORE TODAY, ADD ANOTHER YEAR
IF (DATEDIFF(DAY, GETDATE(), #date) < 0)
BEGIN
SET #date = DATEADD(YEAR, 1, #date)
END
SELECT #date
Here's a solution with PostgreSQL
your_date_calculated = Year * 10000 + Month * 100 + Day
gives you a date like 20090623.
select cast( cast( your_date_calculated as varchar ) as date ) + 1
Here's my version. The core of it is just two lines, using the DATEADD function, and it doesn't require any conversion to/from strings, floats or anything else:
DECLARE #Month TINYINT
DECLARE #Day TINYINT
SET #Month = 9
SET #Day = 7
DECLARE #Result DATETIME
SET #Result =
DATEADD(month, ((YEAR(GETDATE()) - 1900) * 12) + #Month - 1, #Day - 1)
IF (#Result < GETDATE())
SET #Result = DATEADD(year, 1, #Result)
SELECT #Result