简体   繁体   中英

SQL query SUM() AND GROUP BY

I have a MySQL table like this:

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:

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. When I add arrival to the query no more unique acco_id's.

Does anyone know a good Single SQL which can use the table indexes?

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. As else you would need to put it into the group by and thus have non unique accomodation id's.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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