SQL Statement Using Multiple Tables - sql

The database being used for this question is structured as follows with Primary Keys bolded, and Foreign Keys ' '.
Countries (Name, Country_ID, area_sqkm, population)
Teams (team_id, name, 'country_id', description, manager)
Stages (stage_id, took_place, start_loc, end_loc, distance, description)
Riders (rider_id, name, 'team_id', year_born, height_cms, weight_kgs, 'country_id', bmi)
Results ('stage_id', 'rider_id', time_seconds)
I am stuck at the question of:
Q: Create a list (year, numridersborn) where we count the number of riders born in different years. Output columns: year, numridersborn. Order by: year
I am currently at :
SELECT year_born AS "year", COUNT(rider_id) as "numridersborn" WHERE ....
May I know how can I go about getting the solution?
Thank you

year_born is in the rider table already so there is no need to Join here.
Just:
SELECT year_born as year, count(*) as numridersborn
FROM Riders
GROUP BY year_born
ORDER BY year_born;
Which is pretty much what you had already with the addition of the GROUP BY and ORDER BY

Related

Joining section in the From clause

Here,I have used joining section in the from clause ...
select course_id, semester, year, sec_id, avg (tot_cred)
from takes natural join student
where year = 2009
group by course_id, semester, year, sec_id
having count (ID) >= 2
Now, My question is , Is this sql query correct ? If yes then why ? Or If not then why ? Thanks.
Your query is technically correct. However, I would advise you strongly to never using natural join. It is a bug waiting to happen. Why? It uses the names -- and only the names -- of columns in the underlying tables. It does not even use declared foreign key relationships.
Instead, use an explicit on or using clause:
select courseid, semester, year, secid, avg(totcred)
from takes t join
student s
using (studentid)
where year = 2009
group by courseid, semester, year, secid
having count(*) >= 2;
Also:
I assume that the spaces in "course id", "sec id", and "tot cred" are simply typos.
Use table aliases.
Qualify the column names -- that is identify what table they are coming from.

Listing rows which have the same value in a certain column in postgresql

I have two tables, Courses and Faculties.
Courses has columns: ID(primary key), description, level,
instructor_id(foreign key), and semester.
Faculties has columns: faculty_id(primary key), name, date_of_birth,
address, email, and level.
instructor_id in Courses references faculty_id in Faculties.
I'm trying to write a query which lists all the instructors who teach more than one course. As I'm new to SQL in general I'm utterly stumped as to how to go about doing this. There are rows in the Courses table with the same value for instructor_id. Thus far I've already joined the tables like this:
SELECT "Courses".description, "Faculties".name FROM "Courses" INNER JOIN
"Faculties" ON "Courses".instructor = "Faculties".faculty_id;
But I don't know how to filter out the rows which which duplicate values under Instructor column (in other words filter the classes with the same instructor).
This is an aggregation query. If you just want the instructor id, then you can use:
select instructor_id
from courses
group by instructor_id
having count(*) > 1;
To get additional information, join in the other table.

SQL SUM Aggregation with DISTINCT Statement

Table 1: Schema for the bookworm database. Primary keys are underlined. There are some foreign key references to link the tables together; you can make use of these with natural joins.
Author(aid, alastname, afirstname, acountry, aborn, adied).
Book(bid, btitle, pid, bdate, bpages, bprice).
City(cid, cname, cstate, ccountry).
Publisher(pid, pname).
Author_Book(aid, bid).
Publisher_City(pid, cid).
This question has me a little confused, any help is much appreciated.
Find the number of authors of each country.
So far I have tried
SELECT
SUM(DISTINCT acountry) AS total,
COUNT(DISTINCT acountry)AS N
FROM Author;
And received:
ERROR: function sum(character varying) does not exist
LINE 1: select sum(distinct acountry) as total, count(distinct acoun...
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
You can't sum strings. As acountry contains the string value (Assuming country name). And to get the the number of authors of each country. To get the country wise author count you need to use the GroupBy country name and count the rows within that group which you can try as below,
SELECT COUNT(*) AS totalAuthor,
acountry AS Country
FROM Author
GROUP BY acountry
You need to group by country, and count the number of records for each group
SELECT acountry, COUNT(1) as NumberOfAuthors FROM Author GROUP BY acountry

Study Guide questions for database SQL Command

In the relation R(A,B,C,D) if D is multivalued and the apparent key is A, which of the following is not an acceptable way to create a first normal form table for this schema?
a) Decompose R into R1(A,B,C,D) and R2(D)
b) Decompose R into R1(A,B,C) and R2(A,D)
c) Use D as part of the primary key, making the relation have the form R1(A,D,B,C)
d) Determine the maximum number of values there are for D in any record, and include that many columns for D, making the relation have the form R1(A,B,C,D1, D2, … ,Dn)
I have D, at the moment, but don't know it that is right, and for my second question is my command right?
Customer(custId, lastName, firstName, address, phone, creditLimit)
Order(orderNumber, date, total, custID.
LineItem(orderNumber, itemNumber, qtyOrdereD.
Item(itemNumber, itemName, price)
Reference: Sales Database
For the Sales Database in the reference, write the SQL command to find the item numbers of all items ordered by Sue Adams on June 10, 2011.
SELECT lastName, firstName, custID, date, qtyOrdereD
FROM Customer, Order, LineItem
WHERE Date = "June 10, 2011"
For your query, you are simply joining the tables which is wrong since you will get all combinations of values in your tables which is not what you want. You should instead natural join them in order to get the correct entries. The correct query is below:
SELECT lastName, firstName, custID, date, itemNumber
FROM Customer NATURAL JOIN Order NATURAL JOIN LineItem
WHERE DATE = "2011-06-10" AND lastName = 'Adams' AND firstName = 'Sue';

Output a record that appears more than x times

I am a beginner in SQL, and I need help to get the solution for this condition.
Output the name of any person who bought tickets to visit the Park more than 4 days in a single month. (Also, output the month.)
create table visitor(
visitID char(n),
name char(n) not null,
primary key (visitID)
);
create table ticket(
ticketID char(n),
ticketType char(n),
day int(n),
month char(n),
year int(n),
visitID char(n),
primary key (ticketID), foreign key (visitID) references visitor
);
I am unable to test my code, but what I have so far is
SELECT name, month
FROM Visitor NATURAL JOIN Ticket AS t
JOIN (SELECT name, month
FROM Visitor NATURAL JOIN Ticket
GROUP BY month, year
HAVING COUNT(1) > 4
) AS s
ON t.name = s.name AND t.month = s.month;
I don't know if this is right or not.
Please help.
SELECT s.name, t.month
FROM Visitor inner JOIN Ticket AS t
ON t.visitID= s.visitID
group by month, year
having count(day)>4
Your query may be right technically. But the subquery answers your question:
SELECT name, month
FROM Visitor NATURAL JOIN Ticket
GROUP BY month, year
HAVING COUNT(1) > 4;
Two points, though. Don't use natural join. It can do strange things, based on the names of columns in the table. Explicitly name the columns, using on or using. And, in some databases, month and year might be reserved words. So they are bad names for columns. You can quote them (in most databases) with double quotes. So:
SELECT "month", "year"
FROM Visitor INNER JOIN
Ticket
using (VisitorId)
GROUP BY "month", "year"
HAVING COUNT(1) > 4;
The query might need to count distinct dates. In this case, the having clause should be:
HAVING count(distinct "day") > 4
I have just started learning Mysql. I am still going through the basic syntax and everything so cant really help. But don't you think there is a fault in your question. As Name attribute in the visitor table is not unique(and it should not even be unique). So basically your not finding the same person. Your just trying to find different person that have the same name that visited the park 4 times in a month.