SQL使用group by获取记录,包含3个条件

时间:2017-10-17 14:40:32

标签: sql sql-server join group-by inner-join

我正在尝试编写一个查询,根据年龄,性别和状况(糖尿病,高血压等)给出患者就诊人数。获得糖尿病患者和按性别分组的患者以及年龄在45-54岁之间的患者的访问次数。我使用Inner Join来只获取两个表中存在的行。我收到错误:

  

age.Age在选择列表中无效,因为它未包含在中   无论是聚合函数还是GROUP BY子句。

你认为我应该按age.age使用分区吗?

TABLE_A

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

表-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 |
+------------+---------------+------------+

查询

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; 

预期输出

+--------------+--------+-------------+
|  Condition   | Gender | TotalVisits |
+--------------+--------+-------------+
| Diabetes     | M      |           2 |
| Hypertension | F      |           2 |
+--------------+--------+-------------+

1 个答案:

答案 0 :(得分:1)

您可以简化查询过滤WHERE条件

上的年龄

正如Sean Lange所说,使用DATEDADDGETDATE()来更准确地计算年龄。

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]

修改

  

必须更改WHERE条件以解决年龄精度并允许使用索引。