Oracle join a table using a variable field - sql

I'm trying to get the rent rate for which a cage is to be charged with for each month. Here's the logic behind how to get it:
If the rate is defined in the cage table use that table's foreign key to link to the rate table.
If the rate is defined in the rack table use that table's foreign key to link to the rate table.
If the rate is defined in the room table use that table's foreign key to link to the rate table.
If all of the above is false return $0.00 (free rent).
So here are the tables for you to visually understand what I currently have.
Cages
id cage_number rate_id rack_id room_id
----------------------------------------------------
1 FG-12 600 1 1
2 FG-13 600 1 1
3 FG-14 NULL 2 1
4 FG-15 NULL 2 3
Racks
id rack_number rate_id
-----------------------------
1 BN-806 700
2 BN-971 NULL
Rooms
id room_number rate_id
-----------------------------
1 UM-100 800
2 UM-150 900
3 UM-200 NULL
Rates
id rate_id effective_on rate_value
------------------------------------------
1 600 01-Apr-2015 0.67
2 600 01-Oct-2016 0.80
3 700 01-Jan-2016 0.56
4 800 01-Jul-2012 0.61
5 800 01-Dec-2015 0.85
6 900 01-Feb-2015 0.75
7 900 01-Mar-2015 0.79
8 900 01-Apr-2015 0.90
So as you can see there are multiple rows for each rate_id because the price changes from time to time. I already have a query to get the correct rate for each rate_id by checking the effective_on field:
SELECT *
FROM rates r
WHERE r.id = (
SELECT MAX(rr.id) AS curr
FROM rates rr
WHERE rr.rent_id = r.rent_id
AND TRUNC(rr.effective_on) <= TRUNC(sysdate)
)
Let's go back to what my main problem is. I need to join the rate table using the rate_id located on 3 different tables.
Current Solution
My current approach is to join the rate table 3 times using 3 different aliases but since there could be multiple rows for the rate, all 3 instances could have multiple rows each which results in a lot of un-needed rows.
FROM cages c
LEFT JOIN racks rk ON rk.id = c.rack_id
LEFT JOIN rooms rm ON rm.id = c.room_id
LEFT JOIN rates cr ON cr.rate_id = c.rate_id
LEFT JOIN rates rkr ON rkr.rate_id = rk.rate_id
LEFT JOIN rates rmr ON rmr.rate_id = rm.rate_id
Attempted (but miserably failed)
I was thinking of a solution where I would only need to join the rate table once to fix that problem but when I tried it - it failed (as expected).
FROM cages c
LEFT JOIN racks rk ON rk.id = c.rack_id
LEFT JOIN rooms rm ON rm.id = c.room_id
CASE
WHEN c.rate_id IS NOT NULL
THEN LEFT JOIN rates r ON r.rate_id = c.rate_id
WHEN rk.rate_id IS NOT NULL
THEN LEFT JOIN rates r ON r.rate_id = rk.rate_id
WHEN rm.rate_id IS NOT NULL
THEN LEFT JOIN rates r ON r.rate_id = rm.rate_id
END

You can't use a case expression to decide which join condition to use, but you can use a case expression on the right-hand side of the condition, to decide what you're trying to match the rates table's ID against:
FROM cages c
LEFT JOIN racks rk ON rk.id = c.rack_id
LEFT JOIN rooms rm ON rm.id = c.room_id
LEFT JOIN rates r ON r.rate_id =
CASE
WHEN c.rate_id IS NOT NULL THEN c.rate_id
WHEN rk.rate_id IS NOT NULL THEN rk.rate_id
WHEN rm.rate_id IS NOT NULL THEN rm.rate_id
END
But it's simpler to use coalesce() for the outer join condition on the rates table:
LEFT JOIN rates r ON r.rate_id = COALESCE(c.rate_id, rk.rate_id, rm.rate_id)
Or more usefully on a subquery against the rates table that finds the most recent rate for each ID:
select cages.cage_number,
rates.rate_id as rate_id,
nvl(rates.rate_value, 0)
from cages
left join racks on racks.id = cages.rack_id
left join rooms on rooms.id = cages.room_id
left join (
select rate_id,
max(rate_value) keep (dense_rank last order by effective_on) as rate_value
from rates
where effective_on <= trunc(sysdate)
group by rate_id
) rates on rates.rate_id = coalesce(cages.rate_id, racks.rate_id, rooms.rate_id);
CAGE_ RATE_ID COALESCE(RATES.RATE_VALUE,0)
----- ---------- ----------------------------
FG-13 600 .8
FG-12 600 .8
FG-14 800 .85
FG-15 0
The subquery ignores rates that start in the future, as you were already doing; and uses keep dense_rank last to avoid the self-join.
That subquery is then used as an inline view (aliased back to 'rates' for simplicity). The join condition uses coalesce to join on the cage's rate ID if it's set; then the rack ID; then the room ID. Finally there's another coalesce to set the final selected value to zero if there was no match at all.
As #mathguy pointed out, this may end up doing unnecessary work - if the cage has a rate ID there's no point looking at the other tables for that cage. Depending on how selective the data is that may not matter too much, but if it does affect performance you could consider modifying the outer join conditions to eliminate some of them:
from cages
left join racks on racks.id = cages.rack_id
and cages.rate_id is null
left join rooms on rooms.id = cages.room_id
and cages.rate_id is null
and racks.rate_id is null
left join (
...

Here's a different way to get the proper rate_id for each cage. Depending on how many nulls you have in the different tables, it may be more efficient (faster) than doing the left joins on the entire tables. The idea is to collect the rate_id from the cages table when it is not null, and only when it is null to join to the racks table, and only when that doesn't work either, to join only the remaining rows to the rooms table.
I am not showing how to "connect" this to the rates table - either approach in Alex's answer will do. (I would use the second version, again for efficiency.)
with
prep ( id, cage_number, rate_id, room_id ) as (
select c.id, c.cage_number, rk.rate_id, c.room_id
from cages c left outer join racks rk on c.rack_id = rk.id
where c.rate_id is null
)
select id, cage_number, rate_id
from cages
where rate_id is not null
union all
select id, cage_number, rate_id
from prep
where rate_id is not null
union all
select p.id, p.cage_number, rm.rate_id
from prep p left outer join rooms rm on p.room_id = rm.id
where p.rate_id is null
;

Related

Optimize a complex PostgreSQL Query

I am attempting to make a complex SQL join on several tables: as shown below. I have included an image of the dB schema also.
Consider table_1 -
e_id name
1 a
2 b
3 c
4 d
and table_2 -
e_id date
1 1/1/2019
1 1/1/2020
2 2/1/2019
4 2/1/2019
The issue here is performance. From the tables 2 - 4 we only want the most recent entry for a given e_id but because these tables contain historical data (~ >3.5M rows) it's quite slow. I've attached an example of how we're currently trying to achieve this but it only includes one join of 'table_1' with 'table_x'. We group by e_id and get the max date for it. The other way we've thought about doing this is creating a Materialized View and pulling data from that and refreshing it after some period of time. Any improvements welcome.
from fds.region as rg
inner join (
select e_id, name, p_id
from fds.table_1
where sec_type = 'S' AND active_flag = 1
) as table_1 on table_1.e_id = rg.e_id
inner join fds.table_2 table_2 on table_2.e_id = rg.e_id
inner join fds.sec sec on sec.p_id = table_1.p_id
inner join fds.entity ent on ent.int_entity_id = sec.int_entity_id
inner join (
SELECT int_1.e_id, int_1.date, int_1.int_price
FROM fds.table_4 int_1
INNER JOIN (
SELECT e_id, MAX(date) date
FROM fds.table_2
GROUP BY e_id
) int_2 ON int_1.e_id = int_2.fsym_id AND int_1.date = int_2.date
) as table_4 on table_4.e_id = rg.e_id
where rg.region_str like '%US' and ent.sec_type = 'P'
order by table_2.int_price
limit 500;
You can simplify this logic:
(
SELECT int_1.e_id, int_1.date, int_1.int_price
FROM fds.table_4 int_1
INNER JOIN (
SELECT e_id, MAX(date) date
FROM fds.table_2
GROUP BY e_id
) int_2 ON int_1.e_id = int_2.fsym_id AND int_1.date = int_2.date
) as table_4
To:
(SELECT DISTINCT ON (int_1.e_id) int_1.*
FROM fds.table_4 int_1
ORDER BY int_1.e_id, int_1.date DESC
) table_4
This can take advantage of an index on fds.table_4(e_id, date desc) -- and might be wicked fast with such an index.
You also want appropriate indexes for the joins and filtering. However, it is hard to be more specific without an execution plan.

Oracle SQL: SQL join with group by (count) and having clauses

I have 3 tables
Table 1.) Sale
Table 2.) ItemsSale
Table 3.) Items
Table 1 and 2 have ID in common and table 2 and 3 have ITEMS in common.
I'm having trouble with a query that I have made so far but can't seem to get it right.
I'm trying to select all the rows that only have one row and match a certain criteria here is my query:
select *
from sales i
inner join itemssales j on i.id = j.id
inner join item u on j.item = u.item
where u.code = ANY ('TEST','HI') and
i.created_date between TO_DATE('1/4/2016 12:00:00 AM','MM/DD/YYYY HH:MI:SS AM') and
TO_DATE('1/4/2016 11:59:59 PM','MM/DD/YYYY HH:MI:SS PM')
group by i.id
having count(i.id) = 1
In the ItemSale table there are two entries but in the sale table there is only one. This is fine...but I need to construct a query that will only return to me the one record.
I believe the issue is with the "ANY" portion, the query only returns one row and that row is the record that doesn't meet the "ANY ('TEST', 'HI')" criteria.
But in reality that record with that particular ID has two records in ItemSales.
I need to only return the records that legitimately only have one record.
Any help is appreciated.
--EDIT:
COL1 | ID
-----|-----
2 | 26
3 | 85
1 | 23
1 | 88
1 | 6
1 | 85
What I also do is group them and make sure the count is equal to 1 but as you can see, the ID 85 is appearing here as one record which is a false positive because there is actually two records in the itemsales table.
I even tried changing my query to j.id after the select since j is the table with the two records but no go.
--- EDIT
Sale table contains:
ID
---
85
Itemsales table contains:
ID | Position | item_id
---|----------|---------
85 | 1 | 6
85 | 2 | 7
Items table contains:
item_id | code
--------|------
7 | HI
6 | BOOP
The record it is returning is the one with the Code of 'BOOP'
Thanks,
"I need to only return the records that legitimately only have one record."
I interpret this to mean, you only want to return SALES with only one ITEM. Furthermore you need that ITEM to meet your additional criteria.
Here's one approach, which will work fine with small(-ish) amounts of data but may not scale well. Without proper table descriptions and data profiles it's not possible to offer a performative solution.
with itmsal as
( select sales.id
from itemsales
join sales on sales.id = itemsales.id
where sales.created_date >= date '2016-01-04'
and sales.created_date < date '2016-01-05'
group by sales.id having count(*) = 1)
select sales.*
, item.*
from itmsal
join sales on sales.id = itmsal.id
join itemsales on itemsales.id = itmsal.id
join items on itemsales.item = itemsales.item
where items.code in ('TEST','HI')
I think you are trying to restrict the results so that items MUST ONLY have the code of 'TEST' or 'HI'.
select
sales.*
from (
select
s.id
from Sales s
inner join Itemsales itss on s.id = itss.id
inner join Items i on itss.item_id = i.item_id
group by
s.id
where s.created_date >= date '2016-01-04'
and s.created_date < date '2016-01-05'
having
sum(case when i.code IN('TEST','HI') then 0 else 1 end) = 0
) x
inner join sales on x.id = sales.id
... /* more here as required */
This construct only returns sales.id that have items with ONLY those 2 codes.
Note it could be done with a common table expression (CTE) but I prefer to only use those when there is an advantage in doing so - which I do not see here.
If I get it correctly this may work (not tested):
select *
from sales s
inner join (
select i.id, count( i.id ) as cnt
from sales i
inner join itemssales j on i.id = j.id
inner join item u on j.item = u.item and u.code IN ('TEST','HI')
where i.created_date between TO_DATE('1/4/2016 12:00:00 AM','MM/DD/YYYY HH:MI:SS AM') and
TO_DATE('1/4/2016 11:59:59 PM','MM/DD/YYYY HH:MI:SS PM')
group by i.id
) sj on s.id = sj.id and sj.cnt = 1

Complex SQL Query - Joining 5 tables with complex conditions

I have the following tables: Reservations, Order-Lines, Order-Header, Product, Customer. Just a little explanation on each of these tables:
Reservations Contains "reservations" for a billing customer/product combination.
Order-Lines Contains line item detail for orders, including the product they ordered and the qty.
Order-Header Contains header info for orders including the date, customer and billing customer
Product Contains product detail information
Customer Contains Customer detail information.
Below are the tables with their associated fields and sample data:
Reservation
bill-cust-key prod-key qty-reserved reserve-date
10000 20000 10 05/30/2014
10003 20000 5 06/20/2014
10003 20001 15 06/20/2014
10003 20001 5 06/25/2014
10002 20001 5 06/21/2014
10002 20002 20 06/21/2014
Order-Item
order-num cust-key prod-key qty-ordered
30000 10000 20000 10
30000 10000 20001 5
30001 10001 20001 10
30002 10001 20001 5
30003 10002 20003 20
Order-Header
order-num cust-key bill-cust-key order-date
30000 10000 10000 07/01/2014
30001 10001 10003 07/03/2014
30002 10001 10003 07/15/2014
30003 10002 10002 07/20/2014
Customer
cust-key cust-name
10000 Customer A
10001 Customer B
10002 Customer C
10003 Customer D
Product
prod-key prod-name
20000 Prod A
20001 Prod B
20002 Prod C
20003 Prod D
I am attempting to write a query that will show me customer/product combinations that exist in both the reservation and order-item tables. A little snafu is that we have a customer and a billing customer. The reservation and order-header tables contain both the customers, but the order-item table only contains the customer. The results should display the billing customer. Additionally, there can be several reservations and order-items for the same customer/product combination, so I would like to show a total sum of the qty-reserved and the qty-ordered.
Below is an example of my desired output:
bill-cust-key cust-name prod-key prod-name qty-ordered qty-reserved
10000 Customer A 20000 Prod A 10 10
10003 Customer D 20001 Prod B 15 20
This is the query that I have tried and doesn't seem to be working for me.
SELECT customer.cust-key, customer.cust-name, product.prod-key, prod.prod-name,
SUM(order-item.qty-ordered), SUM(reservation.qty-reserved)
FROM ((reservation INNER JOIN order-item on reservation.prod-key = order-item.product-key)
INNER JOIN order-header on reservation.bill-cust-key = order-header.bill-cust-key and
order-item.order-num = order-header.order-num), customer, product
WHERE customer.cust-key = reservation.bill-cust-key
AND product.prod-key = reservation.prod-key
GROUP BY customer.cust-key, customer.cust-name, product.prod-key, product.prod-name
I'm sorry for such a long post! I just wanted to make sure that I had my bases covered!
You want to join your tables like this:
from reservation res join order-header oh on res.bill-cust-key = oh.bill-cust-key
join order-item oi on oi.order-num = oh.order-num
and oi.prod-key = res.prod-key
/* join customer c on c.cust-key = oi.cust-key old one */
join customer c on c.cust-key = oh.bill-cust-key
join product p on p.prod-key = oi.prod-key
I find that it can be very helpful to separate out your output rows from your aggregate rows by using CROSS APPLY (or OUTER APPLY) or simply an aliased inner query if you don't have access to those.
For example,
SELECT
customer.cust-key,
customer.cust-name,
tDetails.prod-key,
tDetails.prod-name,
tDetails.qty-ordered,
tDetails.qty-reserved
FROM customer
--note that this could be an inner-select table in which you join if not cross-join
CROSS APPLY (
SELECT
product.prod-key,
prod.prod-name,
SUM(order-item.qty-ordered) as qty-ordered,
SUM(reservation.qty-reserved) as qty-reserved
FROM reservation
INNER JOIN order-item ON reservation.prod-key = order-item.product-key
INNER JOIN product ON reservation.prod-key = product.prod-key
WHERE
reservation.bill-cust-key = customer.cut-key
GROUP BY product.prod-key, prod.prod-name
) tDetails
There are many ways to slice this, but you started out the right way saying "what recordset do I want returned". I like the above because it helps me visualize what each 'query' is doing. The inner query marked by the CROSS apply is simply grouping by prod orders and reservations but is filtering by the current customer in the outer top-most query.
Also, I would keep joins out of the 'WHERE' clause. Use the 'WHERE' clause for non-primary key filtering (e.g. cust-name = 'Bob'). I find it helps to say that one is a table join, the 'WHERE' clause is a property filter.
TAKE 2 - using inline queries
This approach still tries to get a list of customers with distinct products, and then uses that data to form the outer query from which you can get aggregates.
SELECT
customer.cust-key,
customer.cust-name,
products.prod-key,
products.prod-name,
--aggregate for orders
( SELECT SUM(order-item.qty-ordered)
FROM order-item
WHERE
order-item.cust-key = customer.cust-key AND
order-item.prod-key = products.prod-key) AS qty-ordered,
--aggregate for reservations
( SELECT SUM(reservation.qty-reserved)
FROM reservations
--join up billingcustomers if they are different from customers here
WHERE
reservations.bill-cust-key = customer.cust-key AND
reservations.prod-key = products.prod-key) AS qty-reserved
FROM customer
--get a table of distinct products across orders and reservations
--join products table for name
CROSS JOIN (
SELECT DISTINCT order-item.prod-key FROM order-item
UNION
SELECT DISTINCT reservation.prod-key FROM reservations
) tDistinctProducts
INNER JOIN products ON products.prod-key = tDistinctProducts.prod-key
TAKE 3 - Derived Tables
According to some quick googling, Progress DB does support derived tables. This approach has largely been replaced with CROSS APPLY (or OUTER APPLY) because you don't need to do the grouping. However, if your db only supports this way then so be it.
SELECT
customer.cust-key,
customer.cust-name,
products.prod-key,
products.prod-name,
tOrderItems.SumQtyOrdered,
tReservations.SumQtyReserved
FROM customer
--get a table of distinct products across orders and reservations
--join products table for name
CROSS JOIN (
SELECT DISTINCT order-item.prod-key FROM order-item
UNION
SELECT DISTINCT reservation.prod-key FROM reservations
) tDistinctProducts
INNER JOIN products ON products.prod-key = tDistinctProducts.prod-key
--derived table for order-items
LEFT OUTER JOIN ( SELECT
order-item.cust-key,
order-item.prod-key,
SUM(order-item.qty-ordered) AS SumQtyOrdered
FROM order-item
GROUP BY
order-item.cust-key,
order-item.prod-key) tOrderItems ON
tOrderItems.cust-key = customer.cust-key AND
tOrderItems.prod-key = products.prod-key
--derived table for reservations
LEFT OUTER JOIN ( SELECT
reservations.bill-cust-key,
reservations.prod-key,
SUM(reservations.qty-reserved) AS SumQtyReserved
FROM reservations
--join up billingcustomers if they are different from customers here
WHERE
reservations.bill-cust-key = customer.cust-key AND
reservations.prod-key = products.prod-key) tReservations ON
tReservations.bill-cust-key = customer.cust-key AND
tReservations.prod-key = products.prod-key
Based on your original code and request, here's the starting point of a Progress solution -
DEFINE VARIABLE iQtyOrd AS INTEGER NO-UNDO.
DEFINE VARIABLE iQtyReserved AS INTEGER NO-UNDO.
FOR EACH order-item
NO-LOCK,
EACH order-header
WHERE order-header.order-num = order-item.order-num
NO-LOCK,
EACH reservation
WHERE reservation.prod-key = order-item.prod-key AND
reservation.bill-cust-key = order-header.bill-cust-key
NO-LOCK,
EACH product
WHERE product.prod-key = reservation.prod-key
NO-LOCK,
EACH customer
WHERE customer.cust-key = reservation.bill-cust-key
NO-LOCK
BREAK BY customer.cust-key
BY product.prod-key
BY product.prod-name
:
IF FIRST-OF(customer.cust-key) OR FIRST-OF(product.prod-key) THEN
ASSIGN
iQtyOrd = 0
iQtyReserved = 0
.
ASSIGN
iQtyOrd = iQtyOrd + reservation.qty-ordered
iQtyReserved = iQtyReserved + reservation.qty-reserved
.
IF LAST-OF(customer.cust-key) OR LAST-OF(product.prod-key) THEN
DISPLAY
customer.cust-key
customer.cust-name
product.prod-key
prod.prod-name
iQtyOrd
iQtyReserved
WITH FRAME f-qty
DOWN
.
END.

I need a SQL query for comparing column values against rows in the same table

I have a table called BB_BOATBKG which holds passengers travel details with columns Z_ID, BK_KEY and PAXSUM where:
Z_ID = BookingNumber* LegNumber
BK_KEY = BookingNumber
PAXSUM = Total number passengers travelled in each leg for a particular booking
For Example:
Z_ID BK_KEY PAXSUM
001234*01 001234 2
001234*02 001234 3
001287*01 001287 5
001287*02 001287 5
002323*01 002323 7
002323*02 002323 6
I would like to get a list of all Booking Numbers BK_KEY from BB_BOATBKG where the total number of passengers PAXSUM is different in each leg for the same booking
Example, For Booking number A, A*Leg01 might have 2 Passengers, A* Leg02 might have 3 passengers
Dependent of your RDBMs there might be several options availible. A solution that should work for most is:
SELECT A.Z_ID, A.BK_KEY, A.PAXSUM
FROM BB_BOATBKG A
JOIN (
SELECT BK_KEY
FBB_BOATBKGROM BB_BBK_KEY
GROUP BY BK_KEY
HAVING COUNT( DISTINCT PAXSUM ) > 1
) B
ON A.BK_KEY = B.BK_KEY
If your DBMS support OLAP functions, have a look at RANK() OVER (...)
It's a little counterintuitive, but you could join the table to itself on {BK_KEY, PAXSUM} and pull out only the records whose joined result is null.
I think this does it:
SELECT
a.BK_KEY
FROM
BB_BOATBKG a
LEFT OUTER JOIN BB_BOATBKG b ON a.BK_KEY = b.BK_KEY AND a.PAXSUM = b.PAXSUM
WHERE
b.Z_ID IS NULL
GROUP BY
a.BK_KEY
Edit: I think I missed anything beyond the trivial case. I think you can do it with some really nasty subselecting though, a la:
SELECT
b.BK_KEY
FROM
(
SELECT
a.BK_KEY,
Count = COUNT(*)
FROM
(
SELECT
a.BK_KEY,
a.PAXSUM
FROM
BB_BOATBKG a
GROUP BY
a.BK_KEY,
a.PAXSUM
HAVING
COUNT(*) = 1
) a
GROUP BY
a.BK_KEY
) b
INNER JOIN
(
SELECT
c.BK_KEY,
Count = COUNT(*)
FROM
BB_BOATBKG c
GROUP BY
c.BK_KEY
) c ON b.BK_KEY = c.BK_KEY AND b.Count = c.Count

SQL Syntax Issue with getting sum

Ok I have two tables.
Table IDAssoc has the columnsbill_id, year, area_id.
Table Bill has the columns bill_id, year, main_id, and amount_due.
I'm trying to get the sum of the amount_due column from the bill table for each of the associated area_ids in the IDAssoc table.
I'm doing a select statement to select the sum and joining on the bill_ids. How can I set this up so it will have a single row for each of the associated bills in each area_id from the assoc table. There may be three or four bill_ids associated with each area_id and I need those summed for each and returned so I can use this select in another statement. I have a group by set up for the area_id but it still is returning each row and not summing them up for each area_id. I have the year and main_id specified already in the where clause to return the data that I want, but I can't get the sum to work properly. Sorry I'm still learning and I'm not sure how to do this. Thanks!
Edit- Basically the query I'm trying so far is basically just like the one posted below:
select a.area_id, sum(b.amount_due)
from IDAssoc a
inner join Bill b
on a.bill_id = b.bill_id
where Bill.year = 2006 and bill.bill_id = 11111
These are just arbitrary numbers.
The data this is returning is like this:
amount_due - area_id
.05 1003
.15 1003
.11 1003
65 1004
55 1004
I need one row returned for each area_id with the amount_due summed. The area_id is only in the assoc table and not in the bill table.
select a.area_id, sum(b.amount_due)
from IDAssoc a
inner join Bill b
on a.bill_id = b.bill_id
where b.year = 2006 and b.bill_id = 11111
group by a.area_id
You might want to change inner join to left join if one IDAssoc can have many or no Bill:
select a.area_id, coalesce(sum(b.amount_due),0)
from IDAssoc a
left join Bill b
on a.bill_id = b.bill_id
where b.year = 2006 and b.bill_id = 11111
group by a.area_id
You are missing the GROUP BY clause:
SELECT a.area_id, SUM(b.amount_due) TotalAmount
FROM IDAssoc a
LEFT JOIN Bill b
ON a.bill_id = b.bill_id
GROUP BY a.area_id