[英]Inner join with conditional sum
So I have 3 tables, where I need to get the sum of the price column grouped by the day_of_week
column, and only return the sum for the day_of_week
, that has the lowest sum. 因此,我有3个表,在这里我需要获取按
day_of_week
列分组的price列的总和,并且仅返回具有最低总和的day_of_week
的总和。
In other words, all the venues have a number of services, and through those services, they have available_days and a price. 换句话说,所有场馆都有许多服务,通过这些服务,它们具有可用天数和价格。 So the price for a given day for the venue, is the sum of it's services price for a given day.
因此,该场地在特定日期的价格是其在特定日期的服务价格之和。 I need the sum for a given day, that is the lowest, eg the lowest price of the week.
我需要给定日期的总和,这是最低的,例如,一周的最低价格。
This is my query so far: 到目前为止,这是我的查询:
SELECT * , SUM( ad.price ) AS venue_price
FROM venues AS v
JOIN services AS s ON v.id = s.serviceable_id
JOIN available_days AS ad ON s.id = ad.available_id
WHERE ad.available_type = 'Service'
AND s.type = 'basic'
AND ad.available =1
GROUP BY ad.day_of_week
HAVING venue_price < 500000
ORDER BY venue_price
LIMIT 1
Here is a fiddle: http://sqlfiddle.com/#!2/37ee20/1/0 这是一个小提琴: http ://sqlfiddle.com/#!2/ 37ee20/1/0
This works when I have one venue, but the problem is that it should get ALL the venues, that have a venue_price under 500000. How do i get it to only select the available_days entry with the lowest price, without limiting it to only one venue? 当我有一个场馆时此方法有效,但问题是它应该获得所有会场价低于500000的场馆。我如何只选择价格最低的available_days条目,而不将其限制为仅一个场馆?
If you need record with lowest sum, lets sort it by price
and set LIMIT
to 1
: 如果您需要最低记录的记录,让我们按
price
排序并将LIMIT
设置为1
:
SELECT * , SUM( ad.price ) AS price
FROM venues AS v
JOIN services AS s ON v.id = s.serviceable_id
JOIN available_days AS ad ON s.id = ad.available_id
WHERE ad.available_type = 'Service'
AND s.type = 'basic'
AND ad.available = 1
ORDER BY price ASC
LIMIT 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.