简体   繁体   中英

Query with sum functions

for a little project(hobby purpose) i am building a C# application with a SQL database behind it.

However I am trying to build a query with a sum function which calculates values from a different table.

Here are the relevant tables and sample data

Hotel table

Id, Name            Adress              Zipcode     Phone  
1   Ankunding Group 90 Shelley Terrace  649-6326    86-(672)239-5855
2   Gerlach-Gutmann 50776 Bartillon Road    27109 CEDEX 33-(412)226-8055
3   Breitenberg-Smith   3289 Talisman Avenue    59762   86-(141)636-8780
4   Smitham-Marks   5 Veith Plaza   216282  7-(400)484-7233
5   Beatty LLC  3 Center Pass   940028  212-(310)974-4364

Reservation table

id, customerid,     Startdate   Enddate     Amount of persons
1   163             2016-06-19  2017-04-30  4
2   172             2016-12-02  2016-08-18  5
3   162             2017-01-20  2017-04-08  3
4   66              2017-04-06  2017-01-07  2
5   104             2017-05-07  2016-09-10  2

RoomReservation table

Roomid, reservationid
3       53
3       198
4       178
5       172
5       218

Room table

id, hotelid,  Roomnumber, price 
1   1         1.01        268.83
2   1         1.02        201.28
3   1         1.03        126.64
4   1         1.04        122.56
5   1         1.05        217.41

Now I am trying to make a query to which gives me an overview off income per hotel. So for each hotel I want to get the reservations, and do amount of persons * the price of the room for each room in the hotel.

I've tried different things without success, I read somewhere that I needed to use a subquery but I have no idea how.

I want it to look like;

Hotelname1; income
Hotelname2; income
Hotelname3; income
Hotelname4; income
Hotelname4; income

You can try it whit this query:

select hotel.name,sum(reservation.amount*room.price)
from hotel_table as hotel
inner join room_table as room on (hotel.hotelid=room.hotelid)
inner join roomreservation_table as room_reservation on (room.roomid=room_reservation.roomId)
inner join reservation_table as reservation on (room.reservationId=reservation.reservationid)
group by hotel.hotelid  

Why can't you just do this:

SELECT
    Hotel.Name,
    SUM(Room.Price*Reservation.Amountofpersons)
FROM
    Hotel
    JOIN Room
        ON Hotel.HotelId=Room.HotelId
    JOIN RoomReservation
        ON Room.RoomId=RoomReservation.RoomId
    JOIN Reservation
        ON RoomReservation.ReservationId=Reservation.ReservationId
GROUP BY
    Hotel.Name

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