简体   繁体   English

SQL查询SUM()和GROUP BY

[英]SQL query SUM() AND GROUP BY

I have a MySQL table like this: 我有一个这样的MySQL表:

acco_id | room_id | arrival    | amount | persons | available
1       | 1       | 2015-19-12 | 3      | 4       | 1
1       | 2       | 2015-19-12 | 1      | 10      | 1
1       | 1       | 2015-26-12 | 4      | 4       | 1
1       | 2       | 2015-26-12 | 2      | 10      | 1
2       | 3       | 2015-19-12 | 2      | 6       | 0
2       | 4       | 2015-19-12 | 1      | 4       | 1

What im trying to achieve is a single query with a result like: 我试图实现的是一个单一查询,其结果如下:

acco_id | max_persons_available
1       | 22
2       | 4

I tried using a GROUP BY accommodation_id using a query like: 我尝试使用类似查询的GROUP BY Accommodation_id:

SELECT 
    accommodation_id, 
    SUM(amount * persons) as max_persons_available 
FROM 
    availabilities 
WHERE 
    available = 1
GROUP BY 
    accommodation_id

Only now the result of acco_id uses all arrival dates. 仅现在acco_id的结果使用所有到达日期。 When I add arrival to the query no more unique acco_id's. 当我将到达添加到查询中时,不再有唯一的acco_id。

Does anyone know a good Single SQL which can use the table indexes? 有谁知道一个可以使用表索引的好的Single SQL?

If I'm understanding the question correct (the last part is a bit confusing). 如果我理解正确的问题(最后一部分会引起混淆)。 You want to have the accomodation id and numbers as you have now but limited to specific arrival dates. 您希望拥有与现在一样的住宿编号和住宿编号,但仅限于特定的抵达日期。

If so the following statement should do exactly that as it is not necessary to put arrival into the select if you "just" use it in the where statement. 如果是这样,则下面的语句应该完全这样做,因为如果您只是在where语句中使用到达,则不必将到达放入select中。 As else you would need to put it into the group by and thus have non unique accomodation id's. 否则,您需要将其放入分组依据,从而具有非唯一的住宿ID。

SELECT 
    accommodation_id, 
    SUM(amount * persons) as max_persons_available 
FROM 
    availabilities 
WHERE 
    available = 1 and arrival >= '2015-12-19' and arrival < '2015-10-26'
GROUP BY 
    accommodation_id

I guess (reading your question) what you are looking for is this but im not sure as your question is a bit unclear: 我猜(阅读您的问题)您正在寻找的是这个,但是我不确定,因为您的问题有点不清楚:

SELECT 
    accommodation_id, 
    arrival,
    SUM(amount * persons) as max_persons_available 
FROM 
    availabilities 
WHERE 
    available = 1
GROUP BY 
    accommodation_id, arrival

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM