我正在尝试加入以下两个表:
Table Patient | Table incident
patient.id patient.birthdate | incident.patientid serviceid
1 1/1/2000 | 1 8
2 1/1/1990 | 1 8
3 1/1/2005 | 2 10
4 1/1/1980 | 3 11
5 1/1/2000 | 3 11
6 1/1/1990 | 3 11
7 1/1/1980 | 6 23
8 1/1/2000 | 7 8
为了使所有患者的年龄分开按服务分组。
SELECT serviceid,
SUM(CASE WHEN FLOOR((CAST (GetDate() AS INTEGER) - CAST(patient.birthdate AS INTEGER)) /365.25 ) BETWEEN 0 AND 15 THEN 1 ELSE 0 END) AS [Under 15],
SUM(CASE WHEN FLOOR((CAST (GetDate() AS INTEGER) - CAST(patient.birthdate AS INTEGER)) /365.25 ) BETWEEN 16 AND 18 THEN 1 ELSE 0 END) AS [16-18],
SUM(CASE WHEN FLOOR((CAST (GetDate() AS INTEGER) - CAST(patient.birthdate AS INTEGER)) /365.25 ) BETWEEN 19 AND 23 THEN 1 ELSE 0 END) AS [19-23],
SUM(CASE WHEN FLOOR((CAST (GetDate() AS INTEGER) - CAST(patient.birthdate AS INTEGER)) /365.25 ) BETWEEN 24 AND 30 THEN 1 ELSE 0 END) AS [24-30],
SUM(CASE WHEN FLOOR((CAST (GetDate() AS INTEGER) - CAST(patient.birthdate AS INTEGER)) /365.25 ) BETWEEN 31 AND 40 THEN 1 ELSE 0 END) AS [31-40],
SUM(CASE WHEN FLOOR((CAST (GetDate() AS INTEGER) - CAST(patient.birthdate AS INTEGER)) /365.25 ) BETWEEN 41 AND 50 THEN 1 ELSE 0 END) AS [41-50],
SUM(CASE WHEN FLOOR((CAST (GetDate() AS INTEGER) - CAST(patient.birthdate AS INTEGER)) /365.25 ) BETWEEN 51 AND 65 THEN 1 ELSE 0 END) AS [51-65],
SUM(CASE WHEN FLOOR((CAST (GetDate() AS INTEGER) - CAST(patient.birthdate AS INTEGER)) /365.25 ) > 65 THEN 1 ELSE 0 END) AS [>65]
from patient
inner join incident
on patient.id = incident.patientConcerned
group by serviceid
但我在上面尝试的,计算所有患者的所有事件的年龄,这意味着我不计算不同的患者。 (例如,我计算患者1,两次,患者3,三次)
所以我想加入这两个表,但只有一行。
我该怎么做?
答案 0 :(得分:0)
使用Distinct
运算符。您的查询应该如下:
SELECT Distinct a.id, a.birthdate ,b.patient from
patient a inner join incident b ON a.serviceid=b.serviceid
答案 1 :(得分:0)
而不是sum()
使用count(distinct)
。这是一个例子:
SELECT serviceid,
COUNT(DISTINCT CASE WHEN FLOOR((CAST (GetDate() AS INTEGER) - CAST(patient.birthdate AS INTEGER)) /365.25 ) BETWEEN 0 AND 15
THEN Patient.Id
END) AS [Under 15],
. . .
答案 2 :(得分:0)
而不是group by serviceid
使用group by patient.patient_id