I am trying to show a count for each age which is calculated from a Date of Birth column but the problem is it will only group by date of birth so there are a lot of duplicate ages being shown. Here is my query:
SELECT
DATEDIFF(hh, p.p_dob, GETDATE())/8766 AS Age,
COUNT(DISTINCT s.s_studentreference) AS 'Count'
FROM
moduleenrolment e
INNER JOIN
module m ON m.m_id = e.e_module
INNER JOIN
person p ON p.p_id = e.e_student
INNER JOIN
student s ON s.s_id = p.p_id
WHERE
m.m_reference LIKE '11%'
AND LEN(m.m_reference) <= 12
AND e.e_status IN ('A', 'W', 'C')
GROUP BY
p.p_dob
ORDER BY
p.p_dob DESC
This is a sample for the results
12 1
13 1
14 1
14 1
14 1
14 1
14 1
14 1
14 1
14 1
14 1
What I was looking for was
12 1
13 1
14 9
Group by and order by
DATEDIFF(hh, p.p_dob, GETDATE())/8766instead ofp.p_dobBy grouping by
p.p_dob, you’re effectively grouping by the unique date of birth instead of the calculated age.