Question

I have this university task to create table using SELECT statement from multiple tables, but it's not as simple... here's basic info:

I'm using 2 tables -

CITY(city_ID, name);
PERSON(person_ID, name, surname, city_ID); 
--city_ID is FK indicating in which city person was born.

Now my task is to create new table

STATISTICS(city_ID, city_name, number_of_births);
--number_of_births is basically a count of people born in each city

Problem is that I have to use only SELECT statement to do so.

I've tried something like this: (I'm well aware that this cannot possibly work but as to give you a better idea where I'm stuck)

CREATE TABLE Statistics AS 
(SELECT city.city_ID, city.name as "city_name", number_of_births AS 
                (SELECT COUNT(*) FROM person WHERE person.city_id = city.city_id)
 FROM city, person);
Était-ce utile?

La solution

For SQL Server you can do SELECT * INTO. Something like this:

SELECT
    *
INTO Statistics
FROM (
    SELECT 
        city.city_ID, 
        city.name as "city_name", 
        (SELECT COUNT(*) FROM person WHERE person.city_id = city.city_id) as 'number_of_births'
    FROM city
        inner join person on city.city_id = person.city_id
) t1

Autres conseils

(Posted on behalf of the question author).

Ok, this got really messy. Dave Zych's answer was correct when rewritten in Oracle dialect.

CREATE TABLE Statistics AS SELECT * FROM (
    SELECT DISTINCT
        city.city_ID, 
        city.name AS "City_name",
        (SELECT COUNT(*) FROM person WHERE person.city_ID = city.city_ID) AS "number_of_births"
         FROM city  INNER JOIN person ON city.city_ID = person.city_ID);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top