Grouping in my SQL for a constraint less than 10 - mysql

I am confused on which table I should use and or should I join the tables when attempting this question?
List total number of hotels in the database that have less than 10 rooms.
Hotel (hotelNo, hotelName, city)
Room (roomNo, hotelNo, type, price)
Booking (hotelNo, guestNo, dateFrom, dateTo, roomNo)
Guest (guestNo, guestName, guestAddress)
I have tried by just useing one table Room in my statement
SELECT hotelNo
FROM Room
WHERE roomNo < 10
GROUP BY hotelNo;
Would this be correct or should I use something like this?
SELECT h.hotelNo,r.roomNo
FROM Hotel h JOIN Room r ON h.hotelNo= r.hotelNo
WHERE r.roomNo < 10
GROUP BY hotelNo;

Assuming that all hotels have at least one room, you don't need a join. But, you do need aggregation:
select count(*)
from (select r.hotelno
from rooms r
group by r.hotelno
having count(*) < 10
) r;
The subquery returns the hotels that have fewer than 10 rooms (and are in the rooms table, so they have at least one room).
The outer query counts the number of such hotels.

Check count on the having in order to be applied to the groups, and that count the number of rows returned by that query
SELECT COUNT(*)
FROM (
SELECT hotelRo
FROM Room
GROUP BY hotelNo
HAVING COUNT(*)<10
) AS TMP;

Related

SQL : Call information from another table based on a condition

I have two tables:
One is
that has information about the passenger in airlines, its small, just for the sake of representation
I have another table named
, in this i storage information about the flight of each passenger
The idea is that if the passenger did more than 5 flights i need to display the passenger details
I stated a query in the table "flights" that counts each time the passenger id repeats in the table
SELECT passId, COUNT(passId) as numflights FROM flights GROUP BY passId;
Showing
Problem
I need to update that query ir order that, if the number of flights for a passID is > 5, then it displays their detail information located in the table "passenger"
Use having an IN.
SELECT *
FROM passengers
WHERE passid IN (SELECT passId as numflights FROM flights GROUP BY passId HAVING COUNT(passId) > 5)
if the numbers are high you need to join the tables
SELECT p1.*
FROM passengers p1
INNER JOIN (SELECT passId as numflights FROM flights GROUP BY passId HAVING COUNT(passId) > 5) p2
ON p1.passid = p2.passId
Oner method uses a correlated subquery:
select p.*
from passengers p
where (select count(*)
from flights f
where f.passid = p.passid
) > 5;
In particular, this can take advantage of an index on flights(passid). However, it is worth checking if this is actually faster than other alternatives, such as aggregating first and joining.

Determine total cost per user from 3 Different Tables

I am working on a theatre booking system in MySql (My first SQL project). I have three tables:
Production (contains Title, BasicTicketPrice),
Performance (PerformanceDate, PerformanceTime, Title)
Booking (Email of person who booked, PerformanceDate, PerformanceTime, RowNumber).
Each person booked tickets for two or three performances (using their email to book).
I need to to write a query which will display the prices paid for all booked seats and I need to output the RowNumber, Email of person who booked and the Calculated Price.
I understand that I need to join these tables and make the query display a temporary column called Calculated Price but I don't know how to calculate the price.
I tried this:
SELECT DISTINCT b.RowNumber, b.Email, pr.BasicTicketPrice
FROM booking b, production pr performance p
WHERE p.Title=b.PerfDate*b.PerfTime*b.RowNumber;
SELECT CONCAT (PerfDate, PerfTime, RowNumber) AS BookingID FROM booking;
SELECT RowNumber, Email, CONCAT(PerfDate, PerfTime, RowNumber) AS BookingID FROM booking;
SELECT RowNumber, Email, CONCAT((CONCAT(PerfDate, PerfTime, RowNumber) AS BookingID
FROM booking)BasicTicketPrice*BookingID);
SELECT RowNumber, Email, CONCAT(PerfDate, PerfTime, RowNumber) AS BookingID INTEGER
FROM booking;
SELECT RowNumber FROM booking
LEFT JOIN (SELECT Title FROM performance WHERE '2017-11-01 19:00:00' Email IS NULL);
But it didn't work.
Any suggestions? I will be grateful for any ideas.
Assuming:
One row in Bookings per booked seat
Title to be a suitable primary key for Production
PerformanceDate, PerformanceTime to be a suitable primary composite key for Performance
You'll be looking to join the three tables together as per the keys assumed above. It seems you wish to group the bookings together per performance, by the person booking the tickets - if so, you'll need to use an aggregate to show the seat numbers (I've used GROUP_CONCAT to delimit them), as well as to COUNT the tickets purchased and multiply by the ticket cost.
SELECT
b.Email, prod.Title, per.PerformanceDate, per.PerformanceTime,
GROUP_CONCAT(RowNumber) AS BookedSeats,
COUNT(RowNumber) * prod.BasicTicketPrice AS TotalCost
FROM Booking b
INNER JOIN Performance per
ON b.PerformanceDate = per.PerformanceDate
AND b.PerformanceTime = per.PerformanceTime
INNER JOIN Production prod
ON per.Title = prod.Title
GROUP BY
b.Email, prod.Title, per.PerformanceDate, per.PerformanceTime, prod.BasicTicketPrice
ORDER BY prod.Title, per.PerformanceDate, per.PerformanceTime;
Technically, we should include all non-aggregated columns in the GROUP BY, hence prod.BasicTicketPrice is listed as well.

SQL Query: How to use sub-query or AVG function to find number of days between a new entry?

I have a two tables, one called entities with these relevant columns:
id, company_id ,and integration_id. The other table is transactions with columns id, entity_id and created_at. The foreign keys linking the two tables are integration_id and entity_id.
The transactions table shows the number of transactions received from each company from the entities table.
Ultimately, I want to find date range with highest volume of transactions occurring and then from that range find the average number of days between transaction for each company.
To find the date range I used this query.
SELECT DATE_FORMAT(t.created_at, '%Y/%m/%d'), COUNT(t.id)
FROM entities e
JOIN transactions t
ON ei.id = t.entity_id
GROUP BY t.created_at;
I get this:
Date_FORMAT(t.created_at, '%Y/%m/%d') | COUNT(t.id)
+-------------------------------------+------------
2015/11/09 4
etc
From that I determine the range I want to use as 2015/11/09 to 2015/12/27
and I made this query
SELECT company_id, COUNT(t.id)
FROM entities e
INNER JOIN transactions t
ON e.integration_id = t.entity_id
WHERE tp.created_at BETWEEN '2015/11/09' AND '2015/12/27'
GROUP BY company_id;
I get this:
company_id | COUNT(t.id)
+-----------+------------
1234 17
and so on
Which gives me the total transactions made by each company over this date range. What's the best way now to query for the average number of days between transactions by company? How can I sub-query or is there a way to use the AVG function on dates in a WHERE clause?
EDIT:
playing around with the query, I'm wondering if there is a way I can
SELECT company_id, (49 / COUNT(t.id))...
49, because that is the number of days in that date range, in order to get the average number of days between transactions?
I think this might be it, does that make sense?
I think this may work:
Select z.company_id,
datediff(max(y.created_at),min(created_at))/count(y.id) as avg_days_between_orders,
max(y.created_at) as latest_order,
min(created_at) as earliest_order,
count(y.id) as orders
From
(SELECT entity_id, max(t.created_at) latest, min(t.created_at) earliest
FROM entities e, transactions t
Where e.id = t.entity_id
group by entity_id
order by COUNT(t.id) desc
limit 1) x,
transactions y,
entities z
where z.id = x.entity_id
and z.integration_id = y.entity_id
and y.created_at between x.earliest and x.latest
group by company_id;
It's tough without the data. There's a possibility that I have reference to integration_id incorrect in the subquery/join on the outer query.

MySQL Complex Queries

Hey I've been killing myself trying to figure out how to do these queries. Can someone help me out.
These are the tables I have currently.
BOOKING
HOTEL_NO
GUEST_NO
DATE_FROM
DATE_TO
ROOM_NO
GUEST
GUEST_NO
GUEST_NAME
CITY
ADDRESS
ZIP_CODE
HOTEL
HOTEL_NO
HOTEL_NAME
CITY
ADDRESS
ZIP_CODE
STAR
ROOM
ROOM_NO
HOTEL_NO
ROOM_TYPE
PRICE
And these are the queries I need to do.
-List the guests that have all their bookings (past and present) in the same hotel.
-Create a view VIP-Guest that lists guests who have reservations for only 4 star hotels or
4 star hotels
-Among the VIPs find the guest with the largest total stay (in term of number of days).
Express this as a query with the view and without the view
Can someone help me out?
this should get you started. to post on stackoverflow, you need to come with specific questions or errors or problems. like for the query you posted in the comments up top.... that could be a question in itself: "I have these tables, this one specific goal (question/result set), and I tried this query... it gives me this result or it gives me this error."
BOOKING: HOTEL_NO, GUEST_NO, DATE_FROM, DATE_TO, ROOM_NO
GUEST: GUEST_NO, GUEST_NAME, CITY, ADDRESS, ZIP_CODE
HOTEL: HOTEL_NO, HOTEL_NAME, CITY, ADDRESS, ZIP_CODE, STAR
ROOM: ROOM_NO, HOTEL_NO, ROOM_TYPE, PRICE
all guests and bookings...
-- all guests: select * from guest;
-- all bookings: select * from booking;
select *
from guest
join booking on guest.guest_no = booking.guest_no;
-- which is the same as...
select *
from guest, booking
where guest.guest_no = booking.guest_no;
-- and... your comments query was missing a group by clause
select guest_no, guest_name, count(*) as booking_count
from guest
join booking on guest.guest_no = booking.guest_no
group by guest_no, guest_name;
select guest_no, guest_name, count(distinct hotel_no) as hotel_count
from guest
join booking on guest.guest_no = booking.guest_no
group by guest_no, guest_name
having count(distinct hotel_no) = 1;
and I count(distinct hotel_no) because... they might have 3 bookings at Hotel A and 1 at Hotel B. The basic join would give me 4 rows for that person. I don't care how many bookings. I care how many hotels. So I want to count the distinct occurrences of hotel_no per person (there's that group by) instead of every row.
guests by their stars...
-- so we have to get guest and hotel joined. bc hotel has stars.
-- booking has hotel_no. so... we can use that last query and
-- join in HOTEL to get the star information. in the WHERE you
-- will want to put your filter for the number of stars that you
-- are looking for =4 or >=4 or something like that.
-- you might want to check out DISTINCT to get just a list of names
-- instead of a row for each booking.
number of days they stayed...
-- use the second query.
-- datediff(date_to, date_from) as days_stay gives you the length of stay
-- i don't know what the view is.
-- to get the top length could go two ways... either ORDER BY and LIMIT if there is
-- only one person with the top length (let's say 10 days). if there are many people
-- who have stayed 10 days, you'll need to do a MAX on the days_stay and either join
-- that in or use it in the WHERE as a nested select.
this assumes there is a single highest length of stay. only one person stayed 10 days.
SELECT guest_no, guest_name, datediff(date_to, date_from) days_stayed
FROM vip_guest
join booking on vip_guest.guest_no = booking.guest_no
order by datediff(date_to, date_from) desc
limit 1,1
this should work for many... (i'm not testing these... just kind of looking at it)
SELECT distinct guest_no, guest_name, datediff(date_to, date_from) max_stay
FROM vip_guest
join booking on vip_guest.guest_no = booking.guest_no
where datediff(date_to, date_from) = (
select max(datediff(date_to, date_from)) as days_stayed
from booking )
the nested query gets the maximum stay length of everyone. vip_guest and bookings joined together give us guest and date imfo. we will get all bookings for every vip_guest. so we want to filter it down to where stay lengths == the max stay length. in case a person had multiple 10 day stays (my arbitrary max stay length)... use distinct.
now... thats a good point about the nested query. i don't know what is in your view. it is possible none of the max vip guests had a stay as long as the max stay length. in that case, this query would return nothing.

How to count all row result as 1 in mysql?

I have two tables. "tbl_a" which contain fields of patient and hospital, and "tbl_b" which is the consultation.
Now my problem is to only count the patient that has 4 records in "tbl_b" so that if a patient has 4 records in the "tbl_b" then it count as 1.
I want this result only in use of mysql coz and i need this to run in event scheduler.
In short i want to count all patient that has 4 consultation in every hospital. Can anybody help me on this?
Use this solution:
SELECT patient
FROM tbl_b
GROUP BY patient
HAVING COUNT(1) >= 4
Change the >= to = if you just want patients who have exactly four consultations instead of four or more.
Perhaps you want the count of patients who have four or more consultations... in which case you could just wrap the above SELECT and count the number of rows:
SELECT COUNT(1)
FROM
(
SELECT patient
FROM tbl_b
GROUP BY patient
HAVING COUNT(1) >= 4
) a
Assuming tables patients and consultation Joined by patient_id
SELECT * FROM patients
JOIN (SELECT IF(COUNT(patient_id) = 4, patient_id, NULL) AS con
FROM consultation
GROUP BY patient_id) AS con
ON con.patient_id = patients.patient_id
GROUP BY patient_id
the joined table would get only numbers fro consultations which are 4 and all others are NULL hence the join clause in the case would result in records of patients having consultations total 4 only
hope this helps
Try this ::
Select *, count(1)
from table_a a
inner join table_b b
inner join on (a.patient_id=b.patient_id)
group by b.patient_id having count(1) =4
Try this
SELECT
COUNT(consultation )/4 AS Patient_Number
FROM
tbl_b
GROUP BY
consultation
HAVING
(COUNT(consultation ) % 4) = 0