I have these three tables:
create table Nation ("nationkey" integer,
"name" text,
"regionkey" integer,
"comment" text,
"null" text,
foreign key (regionkey) references Region);
create table Supplier ("suppkey" integer,
"name" text,
"address" text,
"nationkey" integer,
"phone" text,
"acctbal" real,
"comment" text,
"null" text,
foreign key (nationkey) references Nation);
create table Customer ("custkey" integer,
"name" text,
"address" text,
"nationkey" integer,
"phone" text,
"acctbal" real,
"mktsegment" text,
"comment" text,
"null" text,
foreign key (nationkey) references Nation);
I have to write a sql query that returns the names of the nations that have more customers than suppliers. The query needs to be in Sqlite3. I am really new to sql and not sure how to go about doing this.
For a specific nation key, you can get the number of corresponding customers with COUNT:
SELECT COUNT(*)
FROM Customer
WHERE nationkey = ?
The same works for suppliers.
You can then use these COUNT queries as correlated subqueries to compare these values for each Nation
record:
SELECT name
FROM Nation
WHERE (SELECT COUNT(*)
FROM Customer
WHERE nationkey = Nation.nationkey) >
(SELECT COUNT(*)
FROM Supplier
WHERE nationkey = Nation.nationkey)
Another possible solution that uses explicit JOIN
s:
SELECT n.name
FROM Nation n
JOIN Customer c ON n.nationkey = c.nationkey
JOIN Supplier s ON n.nationkey = s.nationkey
GROUP BY n.name
HAVING COUNT(c.nationkey) > COUNT(s.nationkey)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.