COUNT with DATE INTERVALS - tsql

I have this table called Table1 as follows:
UserID Date
1 01/01/09
1 14/01/09
1 25/01/09
1 01/02/09
1 15/02/09
2 02/02/09
2 15/02/09
I am trying to return a result that counts the number of times between the MIN(Date) and 30 days after the MIN(Date) which is DATEADD(day,30,MIN(DATE)). So it would look something like this:
UserID Count
1 3
2 2
This code below is wrong but it expresses what I am trying to achieve:
SELECT COUNT(1) AS Count
FROM Table1
GROUP BY UserID
WHERE Date BETWEEN MIN(Date) AND DATEADD(day,30,MIN(DATE))

SELECT a.UserID, COUNT(a.UserID) AS [Count]
FROM Table1 AS a
INNER JOIN
(
SELECT UserID, MIN([Date]) AS MinDate
FROM Table1
GROUP BY UserID
) AS b
ON a.UserID = b.UserID
WHERE [Date] BETWEEN MinDate AND DATEADD(day, 30, MinDate)
GROUP BY a.UserID

Try this
DECLARE #table TABLE(
UserID INT,
DDate DATETIME
)
INSERT INTO #table (UserID,DDate) SELECT 1, '01 Jan 2009'
INSERT INTO #table (UserID,DDate) SELECT 1, '14 Jan 2009'
INSERT INTO #table (UserID,DDate) SELECT 1, '25 Jan 2009'
INSERT INTO #table (UserID,DDate) SELECT 1, '01 Feb 2009'
INSERT INTO #table (UserID,DDate) SELECT 1, '15 Feb 2009'
INSERT INTO #table (UserID,DDate) SELECT 2, '02 Feb 2009'
INSERT INTO #table (UserID,DDate) SELECT 2, '15 Feb 2009'
SELECT t.UserID,
COUNT(t.UserID)
FROM #table t INNER JOIN
(
SELECT UserID,
MinDate,
DATEADD(dd, 30, MinDate) MinDataAdd30
FROM (
SELECT UserID,
MIN(DDate) MinDate
FROM #table
GROUP BY UserID
) MINDates
) DateRange ON t.UserID = DateRange.UserID
WHERE t.DDate BETWEEN DateRange.MinDate AND DateRange.MinDataAdd30
GROUP BY t.UserID

I think you'll need to use a subquery to get the minimum date. I've shown it below
as a separate query into a variable as I'd probably turn this into a table-valued function.
DECLARE #STARTDATE DATETIME
SELECT #STARTDATE = MIN(DATE) FROM Table1
SELECT COUNT(1) AS Count
FROM Table1
GROUP BY UserID
WHERE Date BETWEEN #STARTDATE AND DATEADD(day,30,#STARTDATE)

I would do it like this:
select a.UserID, count(case when DDate - MinDate <= 30 then 1 end) as Count
from (
select UserID, min(DDate) MinDate
from Table1
group by UserID
) a
inner join Table1 t on a.UserID = t.UserID
group by a.UserID

Related

Use min function without grouping

How can I retrieve the min of a date without group by?
declare #table table
(
SaleDate date
)
insert into #table
select '7/8/2021' union
select '7/21/2021'
declare #dimdate table
(
fulldate date,
WeekNumberOfYear int
)
insert into #dimdate
select '7/4/2021', 28 union
select '7/5/2021', 28 union
select '7/6/2021', 28 union
select '7/7/2021', 28 union
select '7/8/2021', 28 union
select '7/9/2021', 28 union
select '7/10/2021', 28 union
select '7/11/2021', 29 union
select '7/18/2021', 30 union
select '7/19/2021', 30 union
select '7/20/2021', 30 union
select '7/21/2021', 30 union
select '7/22/2021', 30 union
select '7/23/2021', 30 union
select '7/24/2021', 30
select datepart(week, saledate) 'wk',
min(fulldate) as 'Beginning_Week'
from #table t inner join #dimdate d on
datepart(week, saledate) = WeekNumberOfYear
group by datepart(week, saledate), WeekNumberOfYear
How can I retrieve the same result as above without a group by?
Do you mean something like this?
select dt,
(select min(WeekNumberOfYear) from DimDate) as minWeekNumberOfYear
from #table
Just use a windowed aggregate:
SELECT dt,
MIN(dt) OVER () AS MinDt
FROM #table;
You can use MIN() window function if you partition by WeekNumberOfYear and use DISTINCT in the SELECT statement so that there are no duplicates:
SELECT DISTINCT
d.WeekNumberOfYear wk,
MIN(fulldate) OVER (PARTITION BY d.WeekNumberOfYear) Beginning_Week
FROM #table t INNER JOIN #dimdate d
ON DATEPART(week, t.saledate) = d.WeekNumberOfYear;
See the demo.

Create New Rows based on valid to and valid from dates

I have a table that has account number, end of month valid from and end of month valid to columns.
What I need is a table that has account number and a column that has all the end of month dates of when the account was live, inclusive of end of month valid to. The Current Table looks like this
New table will need to be like this
I have tried using a calendar table and an CTE table type query but have had no success.
Any help would be great.
This can be achieved using Using multiple comma separated CTEs in a statement
Query
with t0 (i) AS (select 0 union all select 0 union all select 0 union all select 0 union all select 0 union all select 0),
t1 (i) AS (select 0 from t0 a inner join t0 b on a.i = b.i),
n (i) AS (select row_number()over(order by i) from t1),
Account_details (Account_number,valid_from,valid_to,mth,Live_date)As(
select Account_number,valid_from,valid_to, datediff(month,valid_from,valid_to ) mth, valid_from"Live_date"
from tbl1
union all
select Account_number,valid_from,valid_to, datediff(month,valid_from,valid_to ) mth, EOMONTH (dateadd(month,n.i,valid_from)) "Live_date"
from tbl1
inner join n on 1=1 and n.i between 1 and datediff(month,valid_from,valid_to )
)
select *
from Account_details
where Account_details.Account_number =1
order by Account_details.Account_number
Output
CTE Table t0, t1 and n will generate numbers. This is a best way to generate rows without any data.
Then the CTE table Account_details is used to pull data from the table.
Based on sql on the msdn thread how to get month end date between two dates.
DECLARE #Old AS Table (AccountNumber INT, ValidFrom DATE, ValidTo DATE)
DECLARE #New AS Table (AccountNumber INT, LiveDate DATE)
INSERT INTO #old
SELECT 1, '20130630', '20131130' UNION ALL
SELECT 2, '20130630', '20131231' UNION ALL
SELECT 3, '20120430', '20120531' UNION ALL
SELECT 4, '20170331', '20171130'
SELECT TOP 100 * FROM #old
DECLARE #AccountNumber INT, #ValidFrom DATE, #ValidTo DATE
DECLARE #Cursor CURSOR
SET #Cursor = CURSOR FOR
SELECT AccountNumber, ValidFrom, ValidTo
FROM #old
OPEN #Cursor
FETCH NEXT INTO #Cursor FROM #AccountNumber, #ValidFrom, #ValidTo
WHILE ##FETCH_STATUS = 0
BEGIN
;WITH cteEndMonthDates (MonthEndDate)
AS
(
SELECT eomonth(#ValidFrom) AS MonthEndDate
UNION ALL
SELECT eomonth( dateadd(day, 1, MonthEndDate)) AS MonthEndDate
FROM cteEndMonthDates
WHERE MonthEndDate < eomonth(#ValidTo)
)
INSERT INTO #new (AccountNumber, LiveDate)
SELECT #AccountNumber, MonthEndDate
FROM cteEndMonthDates
FETCH NEXT FROM #Cursor INTO #AccountNumber, #ValidFrom, #ValidTo
END
CLOSE #Cursor
DEALLOCATE #Cursor
SELECT * FROM #New
Edit: Or without the cursor
DECLARE #Old AS Table (AccountNumber INT, ValidFrom DATE, ValidTo DATE)
DECLARE #New AS Table (AccountNumber INT, LiveDate DATE)
INSERT INTO #old
SELECT 1, '20130630', '20131130' UNION ALL
SELECT 2, '20130630', '20131231' UNION ALL
SELECT 3, '20120430', '20120531' UNION ALL
SELECT 4, '20170331', '20171130' UNION ALL
SELECT 5, '20180430', '20190131' UNION ALL
SELECT 6, '20160430', '20180531'
SELECT TOP 100 * FROM #old
;WITH cteEndMonthDates (AccountNumber, MonthEndDate)
AS
(
SELECT AccountNumber, eomonth(ValidFrom) AS MonthEndDate
FROM #Old
UNION ALL
SELECT x.AccountNumber, eomonth( dateadd(day, 1, MonthEndDate)) AS MonthEndDate
FROM cteEndMonthDates x
JOIN #Old o ON o.AccountNumber = x.AccountNumber
WHERE MonthEndDate < eomonth(ValidTo)
)
SELECT AccountNumber, MonthEndDate
FROM cteEndMonthDates
order by AccountNumber, MonthEndDate
This should work.
;WITH Span AS (
SELECT
AccountNumber,
ValidFrom AS Valid
FROM dbo.Input
UNION ALL
SELECT
AccountNumber,
DATEADD(DAY, 1, Span.Valid) AS Valid
FROM Span
WHERE DATEADD(DAY, 1, Span.Valid) <= (SELECT ValidTo FROM dbo.Input WHERE AccountNumber = Span.AccountNumber)
)
SELECT * FROM Span
ORDER BY Span.AccountNumber, Span.Valid
OPTION (MAXRECURSION 0);

Select Max Date in either case statement or where clause

I have 2 columns 1) id (int) and 2) Date. I want to select id on max date. Grouping results in returning both id's/more than one id. Instead i only want to retrieve id on max date .
I am sure there is easier way to do this however below should work fine.
-- create sample data
create table #temp(ID int, courseID int, end_date datetime)
go
insert into #temp
select 1 , 11 , getdate()
union
select 1, 12, getdate()-20
union
select 1, 13, getdate()-40
union
select 2, 13, getdate()-70
union
select 2, 14, getdate()-80
-- create temp table to calculate correct date
select id, max(end_date) as correctDate
into #temp2
from #temp
group by id
-- final desired outup
select #temp2.id , #temp.courseID
from #temp2
inner join #temp
on #temp2.id = #temp.id
and #temp2.correctDate = #temp.end_date
-- drop temp tables
drop table #temp
drop table #temp2
give me a shout if you have any questions
Simpler alternative
-- create sample data
create table #temp(id int, courseID int, end_date datetime)
go
insert into #temp
select
1 , 11 , getdate()
union
select
1, 12, getdate()-20
union
select
1, 13, getdate()-40
union
select
2, 13, getdate()-70
union
select
2, 14, getdate()-80
SELECT * FROM(
SELECT DENSE_RANK() OVER(PARTITION BY id ORDER BY end_date DESC ) sira, id,courseID,end_date FROM #temp
) t WHERE sira = 1
-- drop temp tables
drop table #temp
drop table #temp2

DATEDIFF On Dates

I've been struggling with this but I'm not really good at tsql.
This is what I got, and I can't have the DateTime calculates all right. I'm getting the sum between A and B but not the total sum. For example in the last column I have a 0 which is getting me back to -x.
Here is the procedure, and some of the data are like this:
Code_Procedure date_evenement codes_situation
---------------------------------------------------------------
000079500000 2013-05-21 13:07:00.000 COMCFM
000079500000 2013-05-21 20:24:00.000 PCHCFM
000079500000 2013-05-22 09:58:00.000 PCHCFM
000079500000 2013-05-23 00:00:00.000 AARCFM
000079500000 2013-05-23 00:00:00.000 LIVCFM
000079600000 2013-05-21 13:07:00.000 COMCFM
000079600000 2013-05-21 20:24:00.000 PCHCFM
000079600000 2013-05-22 11:18:00.000 PCHCFM
000079600000 2013-05-23 00:00:00.000 AARCFM
000079600000 2013-05-23 00:00:00.000 LIVCFM
Here is the proc:
DECLARE #COMCFM TABLE(numero_colis VARCHAR(25), date_evenement DATETIME);
INSERT #COMCFM SELECT TOP(5) numero_colis, date_evenement FROM cartitem_colis_postaux_etats WHERE (code_situation = 'PCH' AND code_justification = 'CFM')
WHILE (SELECT COUNT(*) FROM #COMCFM) > 0
BEGIN
DECLARE #Colis TABLE(numero_colis VARCHAR(25), date_evenement DATETIME, code_situation_code_justification NVARCHAR(32));
INSERT #Colis SELECT numero_colis, date_evenement, code_situation + code_justification FROM cartitem_colis_postaux_etats WHERE numero_colis = (SELECT TOP(1) numero_colis FROM #COMCFM) ORDER BY numero_colis, date_evenement
;WITH CTE AS
(
Select DISTINCT
*
,ROW_NUMBER() OVER(PARTITION BY numero_colis ORDER BY date_evenement ASC) Rn FROM #Colis
),CTE1 AS
(
SELECT DISTINCT
A.*
,DATEDIFF(mi, B.date_evenement, A.date_evenement) AS DIFF
FROM CTE A INNER JOIN CTE B On B.Rn + 1 = A.Rn
UNION All
SELECT A.*, 0 FROM CTE A Where Rn = 1
)
SELECT
A.*
,ISNULL((
SELECT
A.DIFF + B.DIFF
FROM CTE1 AS B
WHERE A.numero_colis = B.numero_colis
AND A.Rn = B.Rn + 1), 0) AS Sums
FROM CTE1 AS a
ORDER BY numero_colis, Rn ASC
DELETE FROM #Colis
DELETE FROM #COMCFM WHERE numero_colis = (SELECT TOP(1) numero_colis FROM #COMCFM)
END
I'm not really sure what you would like to achieve. Do you need date differencies as a cummulated value? If you need this, change your BEGIN-END block of your stored procedure with this code
BEGIN
DECLARE #Colis TABLE(numero_colis VARCHAR(25), date_evenement DATETIME, code_situation_code_justification NVARCHAR(32));
INSERT #Colis SELECT numero_colis, date_evenement, code_situation + code_justification FROM cartitem_colis_postaux_etats WHERE numero_colis = (SELECT TOP(1) numero_colis FROM #COMCFM) ORDER BY numero_colis, date_evenement
;WITH CTE AS
(
SELECT DISTINCT
*,
ROW_NUMBER() OVER(PARTITION BY numero_colis ORDER BY date_evenement ASC) Rn
FROM #Colis
),CTE1 AS
(
SELECT A.*, 0 AS CummulatedDiff
FROM CTE A
WHERE Rn = 1
UNION ALL
SELECT DISTINCT A.*, B.CummulatedDiff + DATEDIFF(mi, B.date_evenement, A.date_evenement) AS CummulatedDiff
FROM CTE AS A INNER JOIN
CTE1 AS B ON B.Rn + 1 = A.Rn AND B.numero_colis = A.numero_colis
)
SELECT *
FROM CTE1 AS a
ORDER BY numero_colis, Rn ASC
DELETE FROM #Colis
DELETE FROM #COMCFM WHERE numero_colis = (SELECT TOP(1) numero_colis FROM #COMCFM)
END
I hope this takes you further to your goal.

T-SQL Average of Table Subset

I have a table (in SQL Server 2005) of daily weather data for a single location which includes these columns:
LogDate DATETIME
HighTemp INT
Temp6MonthHighAverage INT
LogDate and HighTemp have data. HighTemp6MonthAverage will be populated with, as the name suggests, the average high temperature for the 6 months ending in LogDate.
There are similar requirements for LowTemp, as well as humidity and several other items, for data spanning decades.
I find myself thinking in circles. Can I derive this average for each row in an UPDATE statement using set operations, or do I need to implement a solution with cursors? I will appreciate any suggestions.
-- select
select HighTemp, LogDate,(select AVG(HighTemp)
from tbl where
DATEDIFF(MONTH, LogDate, t1.LogDate) between 0 and 6)
from tbl t1
-- update
update t1 set Temp6MonthHighAverage = (select AVG(HighTemp)
from tbl where
DATEDIFF(MONTH, LogDate, t1.LogDate) between 0 and 6)
from tbl t1
You can certainly do this with a simple UPDATE:
UPDATE table SET Temp6MonthHighAverage =
(SELECT AVG(HighTemp) FROM table t2 WHERE
t2.LogDate <= table.LogDate
AND t2.LogDate > DATEADD(m, -6, table.LogDate)
)
To avoid re-calculating constantly (since the past will not change), just add a WHERE Temp6MonthHighAverage IS NULL at the end and the same UPDATE can be run as needed to fill in the gaps as new dates are added.
Have a look at something like this
DECLARE #Table TABLE(
LogDate DATETIME,
HighTemp INT,
Temp6MonthHighAverage INT
)
INSERT INTO #Table SELECT '01 Jan 2000', 15, NULL
INSERT INTO #Table SELECT '01 May 2000', 14, NULL
INSERT INTO #Table SELECT '01 Jun 2000', 13, NULL
INSERT INTO #Table SELECT '01 Jul 2000', 12, NULL
INSERT INTO #Table SELECT '01 Dec 2000', 17, NULL
SELECT *
FROM #Table
;WITH DistinctDates AS (
SELECT DATEADD(month,-6,LogDate) StartDate,
LogDate EndDate,
HighTemp
FROM #Table
)
, Aggregates AS (
SELECT dd.EndDate LogDate,
dd.HighTemp,
MAX(t.HighTemp) Temp6MonthHighAverage
FROM DistinctDates dd LEFT JOIN
#Table t ON t.LogDate BETWEEN dd.StartDate AND dd.EndDate
GROUP BY dd.EndDate,
dd.HighTemp
)
UPDATE #Table
SET Temp6MonthHighAverage = a.Temp6MonthHighAverage
FROM #Table t INNER JOIN
Aggregates a ON t.LogDate = a.LogDate
SELECT *
FROM #Table