2017-10-17 97 views
1

我想編寫一個查詢這使我的年齡,性別和狀況(糖尿病,高血壓等)患者就診的號取出使用組記錄。根據性別和年齡在45-54歲之間的患者計算糖尿病患者和患者的訪視次數。我使用Inner Join來僅獲取兩個表中存在的行。我得到的錯誤:SQL用3個條件

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

你認爲我應該使用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

顯示我們的DB模式,樣本數據,當前和預期的輸出。 \t請仔細閱讀[**如何對向**](http://stackoverflow.com/help/how-to-ask) –

+1

你一定要明白,你的年齡計算不準確?如果這個人的生日已經在今年發生過,那麼它就行得通 –

+1

高血壓不是也有2次訪問? –

回答

1

您可以簡化您的查詢過濾年齡對WHERE條件

而且肖恩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] 

編輯

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