Find total number in a specific period of time SQL - tsql

I am trying to find the total number of members in a given period. Say I have the following data:
member_id start_date end_date
1 9/1/2013 12/31/2013
2 10/1/2013 11/12/2013
3 12/1/2013 12/31/2013
4 5/1/2012 8/5/2013
5 9/1/2013 12/31/2013
6 7/1/2013 12/31/2013
7 6/6/2012 12/5/2013
8 10/1/2013 12/31/2013
9 7/8/2013 12/31/2013
10 1/1/2012 11/5/2013
In SQL I need to create a report that will list out the number of members in each month of the year. In this case something like the following:
Date Members Per Month
Jan-12 1
Feb-12 1
Mar-12 1
Apr-12 1
May-12 2
Jun-12 3
Jul-12 3
Aug-12 3
Sep-12 3
Oct-12 3
Nov-12 3
Dec-12 3
Jan-13 3
Feb-13 3
Mar-13 3
Apr-13 3
May-13 3
Jun-13 3
Jul-13 5
Aug-13 4
Sep-13 6
Oct-13 8
Nov-13 6
Dec-13 6
So there is only 1 member from Jan-12 (member id 10) until May-12 when member id 4 joins making the count 2 and so on.
The date range can be all over so I can't specify the specific dates but it is by month, meaning that even if someone ends 12-1 it is considered active for the month for Dec.

I was able to create the following stored procedure that was able to accomplish what I needed:
USE [ValueBasedSandbox]
GO
/****** Object: StoredProcedure [dbo].[sp_member_count_per_month] Script Date: 01/08/2015 12:02:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Create date: 2015-08-01
-- Description: Find the counts per a given date passed in
-- =============================================
CREATE PROCEDURE [dbo].[sp_member_count_per_month]
-- Add the parameters for the stored procedure here
#YEAR int
, #ENDYEAR int
AS
DECLARE #FIRSTDAYMONTH DATETIME
DECLARE #LASTDAYMONTH DATETIME
DECLARE #MONTH INT = 1;
--Drop the temporary holding table if exists
IF OBJECT_ID('tempdb.dbo.##TEMPCOUNTERTABLE', 'U') IS NOT NULL
DROP TABLE dbo.##TEMPCOUNTERTABLE
CREATE TABLE dbo.##TEMPCOUNTERTABLE (
counter INT
, start_date DATETIME2
, end_date DATETIME2
)
--Perform this loop for each year desired
WHILE #YEAR <= #ENDYEAR
BEGIN
--Perform for each month of the year
WHILE (#MONTH <= 12)
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SET #FIRSTDAYMONTH = DATEADD(MONTH, #MONTH - 1, DATEADD(YEAR, #YEAR-1900, 0))
SET #LASTDAYMONTH = DATEADD(MONTH, #MONTH, DATEADD(YEAR, #YEAR-1900, 0)-1)
INSERT INTO dbo.##TEMPCOUNTERTABLE(counter, start_date, end_date)
SELECT COUNT(*) AS counter
, #FIRSTDAYMONTH AS start_date
, #LASTDAYMONTH AS end_date
FROM dbo.member_table
WHERE start_date <= #LASTDAYMONTH
AND end_date >= #FIRSTDAYMONTH
--Increment through all the months of the year
SET #MONTH = #MONTH + 1
END -- End Monthly Loop
--Reset Month counter
SET #MONTH = 1
--Increment the desired years
SET #YEAR = #YEAR + 1
END -- End Yearly Loop
--Display the results
SELECT *
FROM dbo.##TEMPCOUNTERTABLE
-- Drop the temp table
IF OBJECT_ID('tempdb.dbo.##TEMPCOUNTERTABLE', 'U') IS NOT NULL
DROP TABLE dbo.##TEMPCOUNTERTABLE
GO

This should do the trick
with datesCte(monthStart,monthEnd) as
(
select cast('20120101' as date) as monthStart, cast('20120131' as date) as monthEnd
union all
select DATEADD(MONTH, 1, d.monthStart), dateadd(day, -1, dateadd(month, 1, d.monthStart))
from datesCte as d
where d.monthStart < '20140101'
)
select *
from datesCte as d
cross apply
(
select count(*) as cnt
from dbo.MemberDates as m
where m.startDate <= d.monthEnd and m.endDate > d.monthStart
) as x
order by d.monthStart

Related

How do I use a calculated value within a DATEFROMPARTS in SQL

I need a calculated month value within DATEFROMPARTS function. The month has to be seven month prior to CURRENT_TIMESTAMP month.
This is what I tried:
DATEFROMPARTS(Year(CURRENT_TIMESTAMP), Month(CURRENT_TIMESTAMP)-7, 1) as SevenMoAgo;
I will eventually use this in the following expression where '12-01-2018' is:
where RECORDED_SERVICE_STARTTIME > ='12-01-2018'
I later used
declare #CurMo AS INT;
declare #MonPri7 AS INT;
set #CurMo = Month(CURRENT_TIMESTAMP);
set #MonPri7 = (#CurMo -7);
Datefromparts(Year(CURRENT_TIMESTAMP), #MonPri7, 1) as SevenMoAgo;
This also did not work.
I get the following error message:
"Cannot construct data type date, some of the arguments have values which are not valid."
For the second code I get:
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near 'Datefromparts'.
Try this...
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP) - 7, 0)
Let me explain. First off, we need to understand that SQL Server interprets 0 as 1900-01-01 as shown by the following DATEPART functions.
SELECT DATEPART(YEAR, 0) AS Year
, DATEPART(MONTH, 0) AS Month
, DATEPART(DAY, 0) AS Day;
Which returns...
Year Month Day
----------- ----------- -----------
1900 1 1
Therefore, my SQL could be rewritten as...
SELECT DATEADD(MONTH, DATEDIFF(MONTH, '1900-01-01', CURRENT_TIMESTAMP) - 7, '1900-01-01')
Now perhaps it is a little easier to see what is going on here. The DATEDIFF function returns the number number of months between 1900-01-01 and today (CURRENT_TIMESTAMP) which is 1434.
SELECT DATEADD(MONTH, 1434 - 7, '1900-01-01')
Then we subtract 7 from 1434 which is 1427 and add that many months back to 1900-01-01.
SELECT DATEADD(MONTH, 1427, '1900-01-01')
Which yields 2018-12-01.
The reason is #MonPri7 is equal to ZERO when you say (#CurMo -7)
There are many different ways to calculate it, but if you want to fix your logic, you should use this:
declare #CurMo AS INT;
declare #MonPri7 AS INT;
set #CurMo = Month(CURRENT_TIMESTAMP);
set #MonPri7 = (#CurMo -7);
declare #Y int = Year(CURRENT_TIMESTAMP) -- <-- This is new variable
-- if 7 months ago is ZERO then you should go back to prev year December
if #MonPri7 = 0
begin
set #MonPri7 = 12
set #Y = #Y - 1
end
Edit:
declare #SevenMonthsAgo datetime;
select #SevenMonthsAgo = Datefromparts(#Y, #MonPri7, 1);
SELECT yourfields
FROM yourtable
where RECORDED_SERVICE_STARTTIME > = '01-01-2019' and
RECORDED_SERVICE_STARTTIME > = #SevenMonthsAgo

How to find the First, Second, Third and Fourth Saturday in month?

How do I find the first, second, third and fourth saturday of the month?
Ex.: I want to end up with this format...
Blockquote
YYYY, MM, Week#1
Blockquote
YYYY, MM, Week#2
Blockquote
Thanks,
This solution does not depend on Datefirst setting.
declare #d datetime = getdate();
select
dateadd(dd, n, firstSaturday)
from (
select
firstSaturday = dateadd(day, 7-(##datefirst+datepart(weekday, dateadd(day,-1, convert(char(6),#d,112)+'01')))%7, dateadd(day,-1, convert(char(6),#d,112)+'01'))
) t
cross apply (values (0), (7), (14), (21)) q(n)
Here is one way to do it, using a stacked cte to create an inline tally table, with another cte on top of that to generate the months calendar.
Please note that you can change the GETDATE() in the first row code to any date you want (even if it's in the middle of the month) and the code will produce all the Saturdays in that month.
-- Get the current month's start date
DECLARE #MonthStart datetime = DATEADD(MONTH, (DATEDIFF(MONTH, 0, GETDATE())), 0)
;WITH lv0 AS (SELECT 0 g UNION ALL SELECT 0)
,lv1 AS (SELECT 0 g FROM lv0 a CROSS JOIN lv0 b) -- 4
,lv2 AS (SELECT 0 g FROM lv1 a CROSS JOIN lv1 b) -- 16
,lv3 AS (SELECT 0 g FROM lv2 a CROSS JOIN lv2 b) -- 256
,Tally (n) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM lv3)
-- gets all the dates in the current month
,CurrentMonth AS (SELECT TOP (32) dateadd(day, n-1, #MonthStart) As TheDate
FROM Tally
WHERE MONTH(dateadd(day, n-1, #MonthStart)) = MONTH(#MonthStart)
ORDER BY n)
-- gets all the Saturday dates of the current month
SELECT TheDate, DATENAME(WEEKDAY, TheDate)
FROM CurrentMonth
WHERE DATEPART(WEEKDAY, TheDate) = 7 -- Depending on server settings!
If you already have a numbers table, you can use it instead of the stacked cte. If you don't know what is a numbers table and why you should have one, read The "Numbers" or "Tally" Table: What it is and how it replaces a loop by Jeff Moden
You can try this.
SET DATEFIRST 1
DECLARE #MonthId INT = 5
DECLARE #FirstDayOfTheMonth DATE = CONCAT(YEAR(GETDATE()), RIGHT(CONCAT('00', #MonthId),2), '01')
DECLARE #SaturdayId INT = 6
SELECT
DATEADD(DAY, #SaturdayId + WK.ID - DATEPART(WEEKDAY, #FirstDayOfTheMonth), #FirstDayOfTheMonth)
FROM ( VALUES(0),(7),(14),(21),(28)) AS WK(ID)
WHERE
MONTH(DATEADD(DAY, #SaturdayId + WK.ID- DATEPART(WEEKDAY, #FirstDayOfTheMonth),#FirstDayOfTheMonth)) = #MonthId

Adding a Date into a Table TSQL using Weighting

I have a Site Table where each site has a Rating between 1 and 4, I also have a capacity table where I want to add a start date using the rating from the site table, for example
A site with a rating of 1 the Start Date should be 01/05/2010 and a End Date 30/09/2010
A site with a rating of 2 and 3 the Start Date should be 01/04/2010 and a End Date 01/11/2010
A site with a rating of 4 the Start Date should be 01/01/2010 and a End Date 31/12/2010
I have had help with the first two columns already see code below, I now need to add the start date and end date. Can you help?
USE OCCUPANCY
CREATE TABLE Cap1
(PitchType_Skey int,
Site_Skey int)
DECLARE #PitchType_Skey INT
DECLARE #Site_Skey INT
SET #PitchType_Skey = 1
SET #Site_Skey = 1
WHILE (#Site_Skey < 127)
BEGIN
IF #PitchType_Skey = 8
BEGIN
SET #PitchType_Skey = 1
SET #Site_Skey = #Site_Skey + 1
END
IF (#Site_Skey < 127)
BEGIN
INSERT INTO dbo.Cap1 (PitchType_Skey, Site_Skey)
SELECT #PitchType_Skey, #Site_Skey
END
SET #PitchType_Skey = #PitchType_Skey + 1
END
In one command and using ISO dates
INSERT INTO dbo.Cap1 (PitchType_Skey, Site_Skey, StartDate, EndDate)
SELECT
ROW_NUMBER() OVER (ORDER BY Site_Skey),
Site_Skey /*from site table column*/,
CASE rating
WHEN 1 THEN '20100501'
WHEN 4 THEN '20100101'
ELSE '20100401'
END,
CASE rating
WHEN 1 THEN '20100930'
WHEN 4 THEN '20101231'
ELSE '20101101'
END
FROM Site

Returning multiple months of data into one select

I have a question on SQL 2008 which is probably quite easy but I can't see the woods for the trees now.
I am trying to produce a sql based report detailing the last six months of helpdesk issue stats, per application, per office, per month which I then take into ssrs to apply prettiness :o)
Anyway - I have my script, which is fine on a month by month basis, for example;
SELECT distinct t.name_1 'Application',
(select distinct name from location where location_ref = c.location_ref) as office,
Count (t.name_1) as [Call Count],
datename(month, dateadd(month,-2,getdate()))+' '+datename(year, dateadd(month,-2,getdate())) as [Report Month]
FROM call_logging C
Inner Join problem_type t On t.ref_composite = c.ref_composite
AND c.resolve_time between onvert(datetime,convert(varchar,month(dateadd(m,-2,getdate()))) + '/01/' + convert(varchar,year(dateadd(m,-2,getdate()))))
and convert(datetime,convert(varchar,month(dateadd(m,-1,getdate()))) + '/01/' + convert(varchar,year(getdate())))
and c.resolve_group in ('48', '60')
which brings back all of May's issues.
The problem is that t.name_1 (the application in which the issue is for) is dynamic and the list grows or shrinks every month.
I basically need a layout of
APPLICATION OFFICE COUNT JUNE MAY APRIL MARCH FEB JAN
WORD LONDON 20 1 1 2 5 10 1
WORD PARIS 10 2 3 1 2 0 3
EXCEL MADRID 05 0 0 3 2 0 0
etc (if that makes sense on this layout!)
I've gone down the 6 separate reports road but it just doesn't look very nice in ssrs. I've thought about #tmptables but they don't like inserting distinct rows.
SELECT [C].[name_1] AS [APPLICATION]
,COUNT([name_1]) AS [CALL COUNT]
,[l].[location_ref]
,[dbo].[ufn_GetDateTime_CalenderYearMonth]([resolve_time]) AS [StartCalenderYearMonth]
FROM [call_logging] [C] INNER JOIN [problem_type] [t]
ON [t].[ref_composite] = [c].[ref_composite]
AND [c].[resolve_group] IN ('48', '60')
INNER JOIN [location] [l] ON [c].[location_ref] = [l].[location_ref]
WHERE [C].[resolve_time] BETWEEN '2011-01-01' AND GETDATE()
GROUP BY [C].[name_1], [l].[location_ref], [dbo].[ufn_GetDateTime_CalenderYearMonth]([resolve_time])
And the code for ufn_GetDateTime_CalenderYearMonth is:
CREATE FUNCTION [dbo].[ufn_GetDateTime_CalenderYearMonth] (#DateTime datetime)
RETURNS varchar(20)
AS
BEGIN
declare #dateString varchar(20)
declare #yearString varchar(10)
declare #monthString varchar(10)
set #yearString = cast( DATEPART(year, #DateTime) as varchar(10))
if(DATEPART(month, #DateTime) < 10)
set #monthString = '0' + cast( DATEPART(month, #DateTime) as varchar(5) )
else
set #monthString = cast( DATEPART(month, #DateTime) as varchar(5) )
set #dateString = #yearString + '-' + #monthString
RETURN (#dateString)
END
You just slap the resultset in a matrix and group everything by [StartCalenderYearMonth] and it will show numbers for each month from 1st of Jan 2011 till now..

How can i select all dates between date range?

I have one SQL Table with 2 columns as below
Column1: ProductionDate - DateTime - Not NULL
Column2: Quantity - Int - Not NULL
Now There are 2 Records in Table
1-1-2012, 5
1-3-2012, 7
Output of Result should be as below if i give date range StartDate as 1-1-2012 and EndDate as 1-15-2012
1-1-2012 5
1-2-2012 0
1-3-2012 7
1-4-2012 0
1-5-2012 0
1-6-2012 0
.
.
.
1-15-2012 0
Means Query should return all the dates of given range with Quantity and if no entry in Table then 0 for Quantity.
How to Do it? Please suggest with Query
Here's one very optimistic draft on what you can use ( source - here )
declare #startDate datetime;
declare #endDate datetime;
set #startDate = '2012-02-09';
set #endDate = '2012-02-15';
WITH span AS (
SELECT #startDate AS dt
UNION ALL
SELECT DATEADD(dd, 1, dt)
FROM span s
WHERE DATEADD(dd, 1, dt) <= #endDate)
select s.dt, t.Quantity from span s
join table t
on s.dt = t.ProductionDate