是否可以在一次查询中计算此销售报告?考虑到包罗万象的 where 子句,我对 SQL 并没有那么热情,并且在将我的头绕在连接上时遇到了麻烦。
表(假设外键为 1-N):
TABLE contacts
id
TABLE reservations
id
created_at
contact_id
TABLE reservation_trips
id
reservation_id -- never null
amount
quantity
trip_type_id -- never null
TABLE cost_adjustments
id
reservation_trip_id -- never null
cost_type_id -- never null
TABLE trip_types
id
title
TABLE cost_types
id
title
kind
示例:
reservations.created_at >= '2013-01-01T09:00:00+00:00' AND
reservations.created_at < '2014-01-01T09:00:00+00:00' AND
reservation_trips.trip_type_id in (1, 2, 3, 4) AND
cost_adjustments.trip_type_id in (5, 6, 7, 8) AND
contact_id in (9, 10, 11, 12)
结果列:
trip_types.title as trip_type_title,
COUNT(DISTINCT reservations.id) as bookings, -- distinct reservations
SUM(reservations.commissions) as commissions, -- distinct reservations
SUM(reservation_trips.id) as guests, -- distinct reservation_trips
SUM(reservation_trips.amount * reservation_trips.quantity) as gross_sales, -- distinct reservation_trips
SUM(cost_adjustments.amount * cost_adjustments.quantity) as adjustments, -- distinct cost_adjustments where cost_types.kind != 'tax'
SUM(gross_sales + adjustments - commissions) as net_sales
表列如下所示:
TRIP TYPE | BOOKINGS | GUESTS | GROSS SALES | ADJUSTMENTS | COMMISSIONS | NET SALES
谢谢!