我在使用交叉表的报告中有两个查询的联合。报告的目的是列出与每个日期对应的值。
第一个查询返回与日期对应的值。第二个查询返回剩余日期及其值。
最后,完成了两个查询的联合。许多人可能会建议使用单个查询来实现这一点,但我无法通过使用 LEFT JOIN 的单个查询来做到这一点,因为它不返回 NULL 值。即使我得到了这个工作,我拥有的 GROUP BY 子句将在 iReport 中分成两行.. NON NULLS AND NULLS。
所以,我能想到的唯一方法是使用联合。输出看起来像
01/01/2013 02/01/2013 03/01/2013 04/01/2013 05/01/2013
X £120.00 £120.00 £120.00
£0.00 £0.00 .
结果两行是由于 GROUP BY.(rowGroup)。日期是列组。理想情况下,我希望它排成一行。
查询是
SELECT
rates_Booking.date
rates_Booking.amount,
booking.reference
FROM
rates_Booking
LEFT JOIN booking ON booking.reference = rates_Booking.bookingReference
LEFT JOIN unit ON booking.apartment = unit.unit
LEFT JOIN property ON property.property = unit.property
WHERE
rates_Booking.date BETWEEN $P{startDate} AND $P{endDate}
AND $X{IN,property.property,buildings}
AND $X{IN,property.area,location}
AND $X{IN, unit.unit, unit}
UNION
SELECT
rates_Calendar.date
0.00 as amount,
'' as reference
FROM
rates_Calendar,unit
LEFT JOIN property ON property.property = unit.property
LEFT JOIN regions ON regions.region = property.area
# unit to apartments
LEFT JOIN apartments ON (apartments.unit = unit.unit)
LEFT JOIN apartmentTypes ON (apartmentTypes.id = apartments.apartmentTypeId)
WHERE
rates_Calendar.date BETWEEN $P{startDate} AND $P{endDate}
AND rates_Calendar.date NOT IN (
SELECT
rates_Booking.date
FROM
rates_Booking
LEFT JOIN booking ON booking.reference = rates_Booking.bookingReference
LEFT JOIN unit ON booking.apartment = unit.unit
LEFT JOIN property ON property.property = unit.property
LEFT JOIN apartments ON (apartments.unit = unit.unit)
LEFT JOIN apartmentTypes ON (apartmentTypes.id = apartments.apartmentTypeId)
WHERE
rates_Booking.date BETWEEN $P{startDate} AND $P{endDate}
AND $X{IN, unit.unit, unit}
AND $X{IN, apartmentTypes.id,apartmentType}
GROUP BY
rates_Booking.date
)
AND $X{IN,property.property,buildings}
AND $X{IN,property.area,location}
AND $X{IN, unit.unit, unit}
另外,有人可以建议它不需要UNION。我知道使用子查询不会带来最佳性能。但是在 JOINS 的 ON 子句中使用 WHERE 条件并没有帮助。