Hui Hu Ph.D.
Department of Epidemiology
College of Public Health and Health Professions & College of Medicine
February 3, 2020
Subject |
---|
id |
name |
gender |
age |
race/ethnicity |
county_id |
state_id |
County |
---|
id |
name |
median household income |
state_id |
State |
---|
id |
name |
policy |
policy start date |
Primary Key
Logical Key
Foreign Key
SELECT Subject.name, State.name as State_name, State.policy
FROM Subject
JOIN State ON Subject.state_id=State.id
;
SELECT Subject.name, State.name as State_name, County.income
FROM Subject
JOIN State
JOIN County
ON Subject.state_id=State.id
AND Subject.state_id=County.state_id
AND Subject.county_id=County.id
;
1
2
3
C
A
B
<<FULL>> JOIN
=
2
3
A
B
1
C
1
2
3
C
A
B
INNER JOIN
=
2
3
A
B
1
2
3
C
A
B
RIGHT JOIN
=
2
3
A
B
C
1
2
3
C
A
B
LEFT JOIN
=
2
3
A
B
1
SELECT COUNT(id) AS n
FROM Subject;
SELECT COUNT(id) AS n, state_id
FROM Subject
GROUP BY state_id;
SELECT COUNT(DISTINCT state_id) AS nState
FROM Subject
;
SELECT MAX(income) AS maxIncome, state_id
FROM County
GROUP BY state_id
HAVING MAX(income) > 90000;
What's the difference between WHERE and HAVING?
SELECT name,
gender,
CASE WHEN age BETWEEN 1 AND 4 THEN 1
WHEN age BETWEEN 5 AND 8 THEN 2
WHEN age > 8 THEN 3
ELSE NULL
END AS recodeAge
FROM Subject
;