SQL - Return average age depending on visits? - mysql

I'm trying to figure out this task, but after trying and trying i am not able to solve it. Can someone with more SQL experience help me out?
I have 3 tables:
[
The task is to calculate the average age (alter) from each person who visited a restaurant located in Salzburg. If a person visited a restaurant that is located in Salzburg twice, it should be added to the average age (Emily in this case).
Since Piccolo and Stella are located in Salzburg, 4 visits happen overall.
But how do i pull this off in SQL?
How do i count the visits?
Any help is appreciated. Thanks in advance everyone!
MySQL Version: 8.0.20
Using MySQL Workbench.
EDIT 4:
Was able to find the solution on my own more or less, although the answer from #Nick is awesome as well, which is why i accept his answer as correct.
Thank you all so much and #Nick!
Just in case someone runs into the same issue,
my final solution is:
SELECT (AVG(age)) FROM PERSON INNER JOIN ISST ON PERSON.person_name = ISST.person_name INNER JOIN PIZZERIA ON ISST.pizzeria_name = PIZZERIA.pizzeria_name && PIZZERIA.stadt="Salzburg";

Since you want to calculate the average age of all visitors (regardless of whether a person visits a pizzeria in the same city twice), you can just JOIN your visits table to the pizzeria and person tables and average the results:
SELECT AVG(p.alter)
FROM ISST i
JOIN PIZZERIA z ON z.pizzeria_name = i.pizzeria_name
JOIN PERSON p ON p.person_name = i.person_name
WHERE z.stadt = 'Salzburg'
Output:
25.75
Demo on dbfiddle

Related

How to query the most profitable item in a specific year in MySQL

I have a practice problem where I am to write a query to find the top most 15 percent profitable products in the year 2005 from a database. The database does NOT have attributes like "Saleprice, or Purchaseprice". It has tables like PUrchaseProductDetails or SalesOrderDetails, and other stuff with Unitprice, orderquantity, ProdID, LIstPrice, ActualCost, StandardPrice, etc as attributes. I am confused as to which one I should use and how to come up with a formula. I tried to write a query, but got infinitely running results.
SELECT A.ProdID, B.ProdID, A.Unitprice - (B.Unitprice * orderquantity) Profit
FROM SalesOrderDetails A join PurchaseOrderD B
ON A.ProdID = B.ProdID
WHERE year(DateOrdered) = 2005
Group by A.ProdID
I have spent hours on these type of questions and my brain is at a dead end right now. If someone can please direct me to do it the right way, it would really help me out.
SELECT sale.ProdID, sum(sale.Unitprice - buy.Unitprice) * sale.Qty AS profit
FROM SalesOrderDetails AS sale
JOIN PurchaseOrderD AS buy ON ...
WHERE year(...) = 2005
GROUP BY 1
ORDER BY 2 DESC
LIMIT 15

Display date and and id corresponding to maximal third value in SQL

I have 3 tables in my database as you can see below: Travel, a table which contains informations about drivers, Travel, which contains informations about travels, and DroveBy, a table which displays which driver drove which Ttravel (relation between the ID's). I would like to write a query which returns the ID of a driver, its name, and the date he traveled the most. In the example below, I would like to return:
1-Armand-2012-07-18
2-Elish-2012-06-18
3-Armand-2012-07-18.
Thanks a lot
You can take the max of difference between start_time and arrived_time like below query
select d.driver_id, d.name, t.travel_date
from(
select dB.driver_id,
max(timestampdiff(minute,start_time,arrival_time)) maxTime
from droveBy dB
join travel t on dB.travel_id = t.travel_id
group by dB.driver_id)t1
join travel t on t1.maxTime = timestampdiff(minute,t.start_time,t.arrival_time)
join droveBy dB on t1.driver_id = dB.driver_id and t.travel_id = dB.travel_id
join Driver d on dB.driver_id = d.driver_id;
This gave me below result
Hope this would help you out.

MySQL summing totals by state by year

I have been playing around with this for what seems like hours and I can't get the results I want. Here is the query I am having trouble with:
SELECT year.year, dstate,
(SELECT sum(amount) FROM gift
WHERE year.year = gift.year
AND gift.donorno = donor.donorno)
FROM donor, gift, year
WHERE year.year = gift.year
AND gift.donorno = donor.donorno;
This seems redundant. Anyway, I am trying display the total donations (gift.amount) for each state by year.
ex.
1999 GA 500 (donorno 1 from GA donated 200 and donorno 2 from GA donated 300)
1999 FL 400
2000 GA 600
2000 FL 500
...
To clarify donors can be from the same state but I am trying to total the gift amounts for that state for the year it is donated.
Any advice is appreciated. I feel like the answer is right in front of me.
Here is a picture of tables for reference:
This is a very simple join & aggregation problem.
SELECT y.year, d.state, SUM(g.amount) AS total
FROM gift AS g
INNER JOIN year AS y ON y.year=g.year
INNER JOIN donor AS d ON d.donorno=g.donorno
GROUP BY y.year, d.state
You don't need the sub-query in your SELECT clause in order to get the total amount. You can sum it by grouping. (I think the GROUP BY clause is what you're missing. I recommend reading up on it.) What you've done is called a correlated sub-query and it is going to be very slow over large data sets because it has to be calculated row-by-row instead of as a set operation.
Also, please don't use the old style comma join syntax. Instead use the explicit join syntax as shown above. It is much clearer and will help avoid accidental Cartesian products.

SQL Script for Counting Records based on specific criteria and returning the Counts

I'm Trying to count records with specific criteria in my Database to ultimately produce some statistical reports.
My Tables and Fields are:
1- Import Table:bed_ID, unit_ID, mrn, acccount_num, sex, service_ID
2- Beds: bed_ID, unit_ID, bed_type_ID
3- Bed_Type: bed_type_ID, bed_type_description
4- Unit: unit_ID, unit_common_name, program_ID, total_beds...other fields that don't apply.
5- Service: service_ID, service_common_name, program_ID
6- Program: program_ID, program_common_name
I want to create a query that will give me a count of each Bed_Type_Description for each Unit. I also want to get each units total beds and calculate beds available but I'm sure I can figure that out if I get help with this part.
Unit Regular_Bed Escalation_Bed Transfer_Bed Bassinet
-------------------------------------------------------------
Unit1 10 4 2 2
Unit2 12 2 2 0
etc...
etc...
This is what I have, but its only related to one specific Unit:
SELECT
COUNT(dw_test.dbo.Bed_Type.bed_type_description) as 'Total Number of Beds'
FROM
dw_test.dbo.MediTechReport_Bed_Board,
--dw_test.dbo.Unit,
dw_test.dbo.Beds,
dw_test.dbo.Bed_Type
WHERE
dw_test.dbo.MediTechReport_Bed_Board.bed_ID = dw_test.dbo.Beds.bed_ID
--AND
-- dw_test.dbo.MediTechReport_Bed_Board.unit_ID = dw_test.dbo.Unit.unit_ID
AND
dw_test.dbo.Beds.bed_type_ID = dw_test.dbo.Bed_Type.bed_type_ID
AND
dw_test.dbo.MediTechReport_Bed_Board.unit_ID = 'KA2MED'
AND
dw_test.dbo.Bed_Type.bed_type_description = 'Regular';
You'll notice a couple lines related to Unit that are commented out. With these commented out I get a returned value of '5' records which is correct. If i remove the commenting to include these lines it returns a value of '0' which makes no sense to me. If someone can explain this to me that'd be great as well.
My SQL is quite rusty, its been a while. Any assistance is greatly appreciated. Thanks again in advance for all your help.
Maybe something like this?
select t.bed_type_description, COUNT(t.bed_type_description) as 'Total Number Of Beds'
from import As I inner join Beds as b on i.bed_Id = b.bed_Id
inner join Unit as u on i.unit_Id = u.unit_Id
inner join Bed_Type as t on b.bed_type_Id = t.bed_type_Id
where u.unit_Id = 'KA2MED'
group by t.bed_type_description

querying same table twice

I have two tables. One is stock_by_month which keeps records on bookId, stockvalue and reportId. The second table is book; which keeps records on BookId,BookTitle and bookprice.
The reportId is unique for every different month, so for 2010 october is 1, 2010 november is 2 and 2010 december is 3
The Task is I want to generate a report which will include book details and also give the stock value of current month(reportid 3) and the previous month(reportId 2).
I am new to this sort of complexity. I am not sure if that is possible. if it is, I will be very grateful for any help. Thanks
Sounds like you want to use a join. There are plenty of tutorials on SQL out there, so read up on joins and you should see how you can implement your report.
You should join the two tables to get all the information, then group by the reportid. Below is some SQL to get you started but definitely read up on joins as Cameron suggested, and also on 'group by'
SELECT m.bookId, m.stockvalue, m.reportId, b.BookId, b.BookTitle, SUM(b.bookprice) AS total
FROM stock_by_month m
JOIN book b
ON b.PRIMARY_KEY = m.FOREIGN_KEY
GROUP BY m.reportId, m.bookId, m.stockvalue, b.BookId, b.BookTitle, b.bookprice
ORDER BY m.reportId DESC