sql - Join tables resulting only one row -


i trying join following 2 tables:

       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 

in order make age seperation of patients grouped serviceid.

select serviceid,         sum(case when floor((cast (getdate() integer) - cast(patient.birthdate integer)) /365.25 ) between 0 , 15 1 else 0 end) [under 15],         sum(case when floor((cast (getdate() integer) - cast(patient.birthdate integer)) /365.25 ) between 16 , 18 1 else 0 end) [16-18],         sum(case when floor((cast (getdate() integer) - cast(patient.birthdate integer)) /365.25 ) between 19 , 23 1 else 0 end) [19-23],         sum(case when floor((cast (getdate() integer) - cast(patient.birthdate integer)) /365.25 ) between 24 , 30 1 else 0 end) [24-30],         sum(case when floor((cast (getdate() integer) - cast(patient.birthdate integer)) /365.25 ) between 31 , 40 1 else 0 end) [31-40],         sum(case when floor((cast (getdate() integer) - cast(patient.birthdate integer)) /365.25 ) between 41 , 50 1 else 0 end) [41-50],         sum(case when floor((cast (getdate() integer) - cast(patient.birthdate integer)) /365.25 ) between 51 , 65 1 else 0 end) [51-65],         sum(case when floor((cast (getdate() integer) - cast(patient.birthdate integer)) /365.25 ) > 65 1 else 0 end) [>65]  patient inner join incident on patient.id = incident.patientconcerned group serviceid 

but trying above, counts age of patients incidents, meaning not counting distinct patients. (for example counting patient 1, twice , patient 3, 3 times)

so want join these 2 tables, 1 row.

how can that?

instead of sum() use count(distinct). here example:

select serviceid,        count(distinct case when floor((cast (getdate() integer) - cast(patient.birthdate integer)) /365.25 ) between 0 , 15                            patient.id                        end) [under 15],        . . . 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -