Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

TSQL Datediff(dd,MAX(p_effdt),CURRENT_TIMESTAMP)

$
0
0

Hi,

OBJECTIVE: for a group of clients, report the average number of days in which they have been enrolled in a given program.

PROBLEM: the clients are often dropped and later re-enrolled in our programs.  So, I want to use only the most recent enrollment date for each client.  And then calculate an average number of days enrolled.

The data looks like this:

c_id	p_effdt	        p_lapdt
123456	12/19/2013	NULL
234567	11/10/2003	12/23/2003
345678	11/25/2010	NULL
345678	12/16/2010	4/29/2010
456789	11/11/2004	11/30/2004
456789	11/13/2003	12/29/2003

Of course, this: Datediff(dd,MAX(p_effdt),CURRENT_TIMESTAMP)

results in the error: Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

DECLARE @LastProgramEffectiveDate DATETIME
SET @LastProgramEffectiveDate = MAX(program.p_effdt)

SELECT AVG(Datediff(dd,@LastProgramEffectiveDate,CURRENT_TIMESTAMP))
FROM events INNER JOIN program ON events.e_case_no = program.c_id
Error: The multi-part identifier "program.p_effdt" could not be bound.

So that SQL query is not the way to go.  What is the best way to accomplish the above defined objective?

Thank you.


Alpineer8


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>