简体   繁体   中英

sum column values from one table in relation with values of column from another table

So, I have 3 tables

Table H

hotelNo | hotelName

H1 | Greenslopes
H2 | Wynsor
H3 | Red Hills

>Table R

roomNo |hotelNo | price
R1 | H1 | 60
R2 | H1 | 50
R3 | H1 | 75
R4 | H1 | 120
R5 | H1 | 95
R1 | H2 | 85
R2 | H2 | 45
R3 | H2 | 90
R4 | H2 | 80
R5 | H2 | 100
.
.
.

>Table B

hotelNo | roomNo
H1 | R1
H2 | R1
H3 | R1
H4 | R2
H5 | R4
H1 | R3
H2 | R1
H3 | R2
H4 | R2
H5 | R3
H1 | R1
H2 | R5
H3 | R1
H4 | R5
H5 | R1
.
.
.

Now, I need to get the total price for the Rs that H1 has in Table B

The Answer should be something like

hotelNo | Total
H1      | ###

And this is what I have tried:

SELECT B.hotelNo, sum(R.price)
FROM B
INNER JOIN R
    ON B.hotelNo = R.hotelNo
WHERE B.hotelNo = 'H1';

But, it doesn't work. It just sum everything from Table R

Then, I tried this (didn't work either):

SELECT B.hotelNo, B.roomNo + (SELECT sum(R.price)
                                FROM R
                                WHERE B.hotelNo = R.hotelNo) as TotalPrice
FROM B
WHERE B.hotelNo = 'H1';

HELP ME PLEASE!

If your query does not work then you might be missing an additional condition in the ON clause:

SELECT b.hotelNo, SUM(r.price) total_price
FROM Booking b JOIN Room r
ON b.hotelNo = r.hotelNo AND b.roomNo = r.roomNo
WHERE b.hotelNo = 'H1'
GROUP BY b.hotelNo -- you can omit this line in SQLite

See the demo .
Result (for your sample data):

| hotelNo | total_price |
| ------- | ----------- |
| H1      | 195         |

This query should do what you want:

SELECT b.hotelNo, sum(r.price)
FROM Booking b INNER JOIN
     Room r
     ON b.hotelNo = r.hotelNo
WHERE b.hotelNo = 'H1';

Although it is malformed (because the unaggregated column in the SELECT is not in the GROUP BY ), SQLite might accept it. I prefer using an explicit GROUP BY :

SELECT b.hotelNo, sum(r.price)
FROM Booking b JOIN
     Room r
     ON b.hotelNo = r.hotelNo
WHERE b.hotelNo = 'H1'
GROUP BY b.hotelNo;

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