I am beginner at SQL and I am trying to create a query.
I have these tables:
CREATE TABLE Hospital (
hid INT PRIMARY KEY,
name VARCHAR(127) UNIQUE,
country VARCHAR(127),
area INT
);
CREATE TABLE Doctor (
ic INT PRIMARY KEY,
name VARCHAR(127),
date_of_birth INT,
);
CREATE TABLE Work (
hid INT,
ic INT,
since INT,
FOREIGN KEY (hid) REFERENCES Hospital (hid),
FOREIGN KEY (ic) REFERENCES Doctor (ic),
PRIMARY KEY (hid,ic)
);
The query is: What is the average in each country of the number of doctors working in hospitals of that country (1st column: each country, 2nd column: average)? Thanks.
You first need to write a query that counts the doctors per hospital
Based on that query, you can retrieve the average number of doctors per country:
If you have an old DBMS that does not support common table expressions the above can be rewritten as:
Here is an SQLFiddle demo: http://sqlfiddle.com/#!12/9ff79/1
Btw: storing
date_of_birthas an integer is a bad choice. You should use a realDATEcolumn.And
workis a reserved word in SQL. You shouldn’t use that for a table name.