| Best way to get count of unique months with activity [message #635582] |
Wed, 01 April 2015 12:57  |
 |
statey603
Messages: 1 Registered: April 2015 Location: NH
|
Junior Member |
|
|
Hello,
I am working on a report that runs using a date range specified by the user. One piece of data that I must return is the number of unique months that have activity reported. the nature of the activity is such that there might be no activity in a given month or there might be multiple occurrences. I only need to provide a count of the unique months that had activity.
For example, the report span might be 1/1/2014 - 12/31/2014. There are records showing activity for the following dates:
01/15/2014, 1/20/2014,1/25/2014,
03/10/2014,
04/25/2014, 4/30/2014,
06/15/2014,
08/10/2014,
10/20/2014, 10/25/2014,
11/05/2014, 11/15/2014, 11/25/2014
In this case, the result should be 7 unique months.
I have tried a few different SQL statements [below] to get the result I need, but they are slow [all taking about the same amount of time]. I am hoping that someone might be able to suggest a different, faster way to get the result that I need.
Note: In my examples, the date range is fixed. The finished SQL will use begin date and end date parameters.
-- METHOD A [GROUP BY]
SELECT COUNT(*) AS Months_Rptd
FROM
(
SELECT
TO_CHAR(TRUNC(claim_end_dt,'MON'), 'MM/YYYY') AS MonthYear,
COUNT(claim_end_dt) AS ClaimCount
FROM claims_hist_tbl
WHERE trunc(claim_end_dt) BETWEEN to_date('07012014','MMDDYYYY')
AND to_date('06302015','MMDDYYYY')
GROUP BY TRUNC(claim_end_dt,'MON')
HAVING COUNT(claim_end_dt) > 0
);
-- METHOD B [DISTINCT]
SELECT COUNT(*) FROM
(
SELECT DISTINCT(TO_CHAR(TRUNC(claim_end_dt,'MON'), 'MM/YYYY')) AS MonthYear
FROM claims_hist_tbl
WHERE trunc(claim_end_dt) BETWEEN to_date('07012014','MMDDYYYY')
AND to_date('06302015','MMDDYYYY')
);
-- METHOD C
SELECT
COUNT(DISTINCT TO_CHAR(TRUNC(claim_end_dt,'MON'), 'MM/YYYY'))
FROM claims_hist_tbl
WHERE trunc(claim_end_dt) BETWEEN to_date('07012014','MMDDYYYY')
AND to_date('06302015','MMDDYYYY')
[Updated on: Wed, 01 April 2015 13:21] Report message to a moderator
|
|
|
|
|
|
|
|
|
|