select * from tblOrgHours where Agencyid = 74 and Fiscal = 2015 And ActivityDate >= '07/01/2014' And ActivityDate <= '06/30/2015' having min(activitydate) = 7
SELECT
*
FROM tblOrgHours
WHERE Agencyid = 74
AND Fiscal = 2015
AND ActivityDate >= '20140701' -- equal or greater than 1st July 2014
AND ActivityDate < '20140801' -- less than 1st August 2014, do NOT use equal here
Please use date ranges the right way:the best practice with date and time ranges is to avoid BETWEEN and to always use the form:Itzik Ben-Gan
WHERE col >= '20120101' AND col < '20120201'
This form works with all types and all precisions, regardless of whether the time part is applicable.
declare @st as date, @fin as date
set @st = '20140701'
set @fin = dateadd(month,1,@st) -- with @st 1st July 2014, then @fin is 1st August 2014
SELECT
COUNT(CASE
WHEN ActivityDate >= @st
AND ActivityDate < @fin -- less than 1st August 2014, do NOT use equal here
THEN ActivityDate
END) AS count_of
FROM tblOrgHours
WHERE Agencyid = 74
AND ActivityDate < @fin -- less than 1st August 2014, do NOT use equal here
HAVING
COUNT(CASE
WHEN ActivityDate < @st THEN ActivityDate END) = 0
;
The best way for this type of need to for you to provide "sample data" and an "expected result", then we do have a way to test.
DECLARE @st AS date
, @fin AS date
SET @st = '20140701'
SET @fin = DATEADD(MONTH, 1, @st) -- with @st 1st July 2014, then @fin is 1st August 2014
SELECT
COUNT(*) AS count_of
FROM (
SELECT
employee_id
FROM tblOrgHours
WHERE Agencyid = 74
AND ActivityDate < @fin -- less than 1st August 2014, do NOT use equal here
GROUP BY
employee_id
HAVING COUNT(CASE
WHEN ActivityDate < @st THEN ActivityDate END) = 0
) sq;
HourID Agency AgencyID Program ActivityID RegID ActivityDate Hours HourTimeFrom HourTimeTo SubGroup ParticipantHour VolunteerHour Fiscal EntryTime
180 Administrator 74 CSW 3 35 7/3/2014 1 00:00.0 00:00.0 1 0 2015 7/3/2014
181 Administrator 74 CSW 3 9 7/3/2014 1 00:00.0 00:00.0 1 0 2015 7/3/2014
183 Administrator 74 CSW 3 6 7/3/2014 1 00:00.0 00:00.0 1 0 2015 7/3/2014
185 Administrator 74 CSW 3 3 7/3/2014 1 00:00.0 00:00.0 1 0 2015 7/3/2014
SELECT
COUNT(DISTINCT RegID)
FROM (
SELECT
RegID
, MIN(ActivityDate) OVER (PARTITION BY RegID) AS RegStartMonth
FROM tblOrgHours
WHERE fiscal = 2015 AND Agency = 74
) sq
WHERE MONTH(RegStartMonth) = 7
;
Second, to filter by month you need to extract month from the date. In SQL Server you need to use DATEPART function.
As I understand you correctly, you want to retrieve the records for the whole year, but at the same time you want to see which one of those originated in July. For this exercise the best approach is to use a WINDOW Function.
Open in new window
The minActivity column will contain the date you are after. However, you will not be able to use it in the WHERE clause straight away. You will have to use a sub-query:Open in new window
Alternatively, you can use a CTE:Open in new window