I've got two SQL queries. One returns all the payments made to a company for a swimming event The other gets all the seating payments (separate from the first).
The first one has a virtual table structure of
carnivalId, buildingCode, TotalRaces, TotalIncome
The second is
carnivalId, SeatCosts
I want to combine them into one table so the query returns in the format of
carnivalId, buildingCode, TotalRaces, TotalIncome, SeatCosts
I've looked into UNION, but it doesn't seem to be the correct approach as the two queries have different return structures.
I've tried joining the two with an inner join on carnivalId, but it just errors -
SELECT c.carnivalId, c.buildingCode, COUNT(r.raceId) as TotalRaces, SUM(p.amountPaid) as TotalIncome
FROM Carnival c, Race r, Payment p, Entry e
WHERE r.carnivalId = c.carnivalId
AND e.raceId = r.raceId
AND p.payId = e.payId
INNER JOIN (SELECT c.carnivalId, SUM(s.seatsBought*st.seatCost)
FROM Carnival c, SeatsAvailable s, SeatType st
WHERE carnivalId = c.carnivalId
AND st.seatType = s.seatType
GROUP BY c.carnivalId, c.buildingCode) SeatingCosts ON c.carnivalId = SeatingCosts.carnivalId
GROUP BY c.carnivalId, c.buildingCode;
I also tried combining the two queries into one, but it made all the returned values completely wrong (it looks like it multiplied all the values in the first by the number of rows in the seatsBought result
SELECT c.carnivalId, c.buildingCode, COUNT(r.raceId) as TotalRaces, SUM(p.amountPaid) as TotalIncome, SUM(s.seatsBought*st.seatCost) as SeatCosts
FROM Carnival c, Race r, Payment p, Entry e, SeatsAvailable s, SeatType st
WHERE r.carnivalId = c.carnivalId
AND e.raceId = r.raceId
AND p.payId = e.payId
AND s.carnivalId = c.carnivalId
AND st.seatType = s.seatType
GROUP BY c.carnivalId, c.buildingCode;
First query -
SELECT c.carnivalId, c.buildingCode, COUNT(r.raceId) as TotalRaces, SUM(p.amountPaid) as TotalIncome
FROM Carnival c, Race r, Payment p, Entry e
WHERE r.carnivalId = c.carnivalId
AND e.raceId = r.raceId
AND p.payId = e.payId
GROUP BY c.carnivalId, c.buildingCode;
Second query -
SELECT c.carnivalId, SUM(s.seatsBought*st.seatCost) as SeatCosts
FROM Carnival c, SeatsAvailable s, SeatType st
WHERE s.carnivalId = c.carnivalId
AND st.seatType = s.seatType
GROUP BY c.carnivalId, c.buildingCode;