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 |
+--------------+--------+-------------+
顯示我們的DB模式,樣本數據,當前和預期的輸出。 \t請仔細閱讀[**如何對向**](http://stackoverflow.com/help/how-to-ask) –
你一定要明白,你的年齡計算不準確?如果這個人的生日已經在今年發生過,那麼它就行得通 –
高血壓不是也有2次訪問? –