如何停止我的MySQL查询为一个引用生成两行?

时间:2011-09-06 12:51:39

标签: mysql sql

我有以下MySQL查询获取代理的所有预订,以及预订的所有房间并执行一些简单的计算:

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

列出了表格,因为booking_record有1个代理(agentref - &gt; a.code)。代理商可能有很多预订,预订可能有很多房间。在这种特殊情况下,我的收入和预订都是不正确的,因为如果单个预订的房间超过1个,则该行将被退回多次(因此,基本价格计算两次,预订计算两次等)。 / p>

我有什么想法可以返回正确的信息吗?

谢谢,丹尼尔。

1 个答案:

答案 0 :(得分:2)

怎么样?

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

请注意,正如@JNK所指出的,此代码基于a.code是表agent的唯一键或主键的假设。如果它是正确的。
如果不是,它将产生不确定的结果。