How do I stop my MySQL query generating two rows for one reference?
I have the following MySQL query which gets all the bookings for an agent, and all the rooms for a booking and performs some simply calculations:
Select a.code, a.name, a.areacode, a.agentgroup,
Sum(br.basicprice) As TotalRevenueYTD,
Sum(b.adults + b.children + b.infants) As Pax,
Count(br.bookingref) As Bookings
From booking_record br
Inner Join agent a On br.agentref = a.code
Inner Join bookingroom b On b.bookingref = br.bookingref
Where br.bookingdate > '2011-01-01' And br.bookingdate < Date(Now())
Group By br.agentref
The tables are set out so as a booking_record has 1 agent (agentref -> a.code). An agent may have many bookings, and a booking may have many rooms. In this particular case my revenue and bookings are coming out incorrect because if a single booking has more than 1 room, the row is returned more than once (and as such, the basicprice is counted twice,开发者_JAVA技巧 the booking is counted twice etc).
Any ideas how I can return the correct information?
Thanks, Daniel.
How about?
SELECT a.code, a.name, a.areacode, a.agentgroup
, Sum(br.basicprice) As TotalRevenueYTD
, sum(b1.pax) As Pax
, Count(br.bookingref) As Bookings
FROM booking_record br
INNER JOIN agent a On br.agentref = a.code
INNER JOIN (
SELECT b.bookingref, Sum(b.adults + b.children + b.infants) as pax
FROM bookingroom b
GROUP BY b.bookingref) AS b1 ON b1.bookingref = br.bookingref
WHERE br.bookingdate >= '2011-01-01'
AND br.bookingdate <= Date(Now())
GROUP BY a.code
Note that as @JNK points out, this code is based on the assumption that a.code is a unique or primary key of table agent
. If it is it will work correct.
If is is not it will yield indeterminite results.
精彩评论