1

I'm trying to write a query which gives me the number of patient visits by age, gender and condition(Diabetes, Hypertension etc). Get the visit count for patients having diabetes and group by gender and patients who fall between the age range of 45-54. I used Inner Join to get only the rows which are present in both tables. I get the error:

age.Age is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Do you think I should use partition by age.age?

TABLE_A

+------------+------------+------------+
| Member_Key | VisitCount |    date    |
+------------+------------+------------+
|       4000 |          1 | 2014-05-07 |
|       4000 |          1 | 2014-05-09 |
|       4001 |          2 | 2014-05-08 |
+------------+------------+------------+

TABLE_B

+------------+--------------+
| Member_Key |  Condition   |
+------------+--------------+
|       4000 | Diabetes     |
|       4000 | Diabetes     |
|       4001 | Hypertension |
+------------+--------------+

TABLE_C

+------------+---------------+------------+
| Member_Key | Member_Gender | Member_DOB |
+------------+---------------+------------+
|       4000 | M             | 1970-05-21 |
|       4001 | F             | 1968-02-19 |
+------------+---------------+------------+

Query

SELECT c.conditions,
       age.gender,
       CASE
           WHEN age.age BETWEEN 45 AND 54
           THEN SUM(act.visitcount)
       END AS age_45_54_years
FROM table_a act
     INNER JOIN
(
    SELECT DISTINCT
           member_key,
           conditions
    FROM table_b
) c ON c.member_key = act.member_key
     INNER JOIN
(
    SELECT DISTINCT
           member_key,
           member_gender,
           DATEPART(year, '2017-10-16')-DATEPART(year, member_dob) AS Age
    FROM [table_c]
) AS age ON age.member_key = c.member_key
GROUP BY c.conditions,
         age.member_gender; 

Expected Output

+--------------+--------+-------------+
|  Condition   | Gender | TotalVisits |
+--------------+--------+-------------+
| Diabetes     | M      |           2 |
| Hypertension | F      |           2 |
+--------------+--------+-------------+
shockwave
  • 3,074
  • 9
  • 35
  • 60

1 Answers1

1

You can simplify your query filtering the age on the WHERE condition

And as Sean Lange said, use DATEDADD and GETDATE() to calculate the age more accurately.

SQL DEMO

SELECT [Condition], 
       [Member_Gender] as [Gender], 
       SUM([VisitCount]) as [VisitCount]
FROM TableA A
JOIN (SELECT DISTINCT [Member_Key], [Condition] 
      FROM TableB) B 
  ON A.[Member_Key] = B.[Member_Key]
JOIN TableC C 
  ON A.[Member_Key] = C.[Member_Key]
WHERE [Member_DOB] BETWEEN DATEADD(year, -50 , GETDATE())
                       AND DATEADD(year, -45 , GETDATE())
GROUP BY [Condition], [Member_Gender]

EDIT

Have to change the WHERE condition to solve the age precision and allow index use.

Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118