Complex SQL Query - Joining 5 tables with complex conditions - sql

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.

Related

Oracle join a table using a variable field

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
;

Two group by tables stich another table

I have 3 tables I need to put together.
The first table is my main transaction table where I need to get distinct transaction id numbers and company id. It has all the important keys. The transaction ids are not unique.
The second table has item info which is linked to transaction id numbers which are not unique and I need to pull items.
The third table has company info which has company id.
Now I've sold some of these with the first one through a group by id. The second through a subquery which creates unique ids and joins onto the first one.
The issue I'm having is the third one by company. I cannot seem to create a query that works in the above combinations. Any ideas?
As suggested here is my code. It works but that's because for the company I used count which doesn't give the correct number. How else can I get the company number to come out correct?
SELECT
dep.ItemIDAPK,
dep.TotalOne,
dep.company,
company.vendname,
appd.ItemIDAPK,
appd.ItemName
FROM (
SELECT
csi.ItemIDAPK,
sum(f.TotalOne) as TotalOne,
count(f.DimCurrentcompanyID) company
FROM dbo.ReportOne F with (nolock)
INNER JOIN dbo.DSaleItem csi with (nolock)
on f.DSaleItemID = csi.DSaleItemID
INNER JOIN dbo.DimCurrentcompany cv
ON f.DimCurrentcompanyID = cv.DimCurrentcompanyID
INNER JOIN dbo.DimDate dat
on f.DimDateID = dat.DimDateID
where (
dat.date >='2013-01-29 00:00:00.000'
and dat.date <= '2013-01-30 00:00:00.000'
)
GROUP BY csi.ItemIDAPK
) as dep
INNER JOIN (
SELECT
vend.DimCurrentcompanyID,
vend.Name vendname
FROM dbo.DimCurrentcompany vend
) As company
on dep.company = company.DimCurrentcompanyID
INNER JOIN (
SELECT
c2.ItemIDAPK,
ItemName
FROM (
SELECT DISTINCT ItemIDAPK
FROM dbo.dimitem AS C
) AS c1
JOIN dbo.dimitem AS c2 ON c1.ItemIDAPK = c2.ItemIDAPK
) as appd
ON dep.ItemIDAPK = appd.ItemIDAPK
For further information my output is the following example, I know the code executes and the companyid is incorrect as I just put it with a (count) in their to make the above code execute:
Current Results:
Item Number TLS CompanyID Company Name Item Number Item Name
111111 300 303 Johnson Corp 29323 Soap
Proposed Results:
Item Number TLS CompanyID Company Name Item Number Item Name
111111 300 29 Johnson Corp 29323 Soap

Calculate value in the query by values from two tables

I have product table like this
PRODUCT_ID PACK_SIZE PACK_PRIZE
3000 5 2.5
3001 5 2.5
3002 5 2.5
3003 5 2.5
Order table
order_id client_id
75001 1024
75002 1033
75003 1030
ITEMS Table
ORDER_ID PRODUCT_ID NUMBER_ORDERED
75001 3936 2
75001 3557 5
75001 3012 3
75001 3236 4
Client Table
CLIENT_ID LAST_NAME STATUS
1021 Smith private
1022 Williams corporate
1023 Browne private
1024 Tinsell corporate
These are sample data I just added these just to show sample data.
I want to select top 2 private clients who has done the orders which are having higher values.
I have problem in selecting orders with max sold amount.
Here's what I'm trying to do.
In this I'm trying to get the Client IDS
SELECT CLIENTS.CLIENT_ID
FROM ORDERS
INNER JOIN ITEMS ON ORDERS.ORDER_ID=ITEMS.ORDER_ID
INNER JOIN PRODUCTS ON ITEMS.PRODUCT_ID =PRODUCTS.PRODUCT_ID
INNER JOIN CLIENTS ON ORDERS.CLIENT_ID = CLIENTS.CLIENT_ID
WHERE ( )
In this i'm trying to select top 2 orders
SELECT TOP 2 ORDERS.ORDER_ID FROM ORDERS
INNER JOIN ITEMS ON ORDERS.ORDER_ID=ITEMS.ORDER_ID
INNER JOIN PRODUCTS ON ITEMS.PRODUCT_ID =PRODUCTS.PRODUCT_ID
WHERE ((PRODUCTS.PACK_PRIZE/PRODUCTS.PACK_SIZE)*(ITEMS.NUMBER_ORDERED));
Gives me errors
FROM Key word not found where expected.
What I want to do is select the order ids from orders which are having highest total and which are not from same client, total should be calculated by finding the unit price by dividing pack_price from pack_size and multiplying it by number_ordered from the items table which is having the matching order id. The ordered clients should be corporate clients.
I'm using oracle 11g.
pack_prize is number pack_size is number
number_ordered is number data type
Oracle doesn't support top 2. Instead use rownum and a subquery:
WITH CTE as (
SELECT ORDERS.ORDER_ID, PRODUCTS.PACK_PRIZE, PRODUCTS.PACK_SIZE, ITEMS.NUMBER_ORDERED
FROM ORDERS INNER JOIN
ITEMS
ON ORDERS.ORDER_ID = ITEMS.ORDER_ID INNER JOIN
PRODUCTS
ON ITEMS.PRODUCT_ID = PRODUCTS.PRODUCT_ID
)
SELECT ORDER_ID
FROM (SELECT CTE.*
FROM CTE
ORDER BY (PACK_PRIZE/PACK_SIZE) * NUMBER_ORDERED DESC
) t
WHERE rownum <= 2;
I'm guessing that the strange where expression is what you are using to determine the best rows.
TOP does not work in oracle. You can use the virtual column ROWNUM or the function ROW_NUMBER() OVER() to get similar functionality.

Query Returning SUM of Quantity or 0 if no Quantity for a Product at a given date

I have the following 4 tables:
----------
tblDates:
DateID
30/04/2012
01/05/2012
02/05/2012
03/05/2012
----------
tblGroups:
GroupID
Home
Table
----------
tblProducts:
ProductID GroupID
Chair Home
Fork Table
Knife Table
Sofa Home
----------
tblInventory:
DateID ProductID Quantity
01/05/2012 Chair 2
01/05/2012 Sofa 1
01/05/2012 Fork 10
01/05/2012 Knife 10
02/05/2012 Sofa 1
02/05/2012 Chair 3
03/05/2012 Sofa 2
03/05/2012 Chair 3
I am trying to write a query that returns all Dates in tblDates, all GroupIDs in tblGroups and the total Quantity of items in each GroupID.
I manage to do this but only get Sum(Quantity) for GroupID and DateID that are not null. I would like to get 0 instead. For exemple for the data above, I would like to get a line "02/05/2012 Table 0" as there is no data for any product in "Table" group on 01/05/12.
The SQL query I have so far is:
SELECT tblDates.DateID,
tblProducts.GroupID,
Sum(tblInventory.Quantity) AS SumOfQuantity
FROM (tblGroup
INNER JOIN tblProducts ON tblGroup.GroupID = tblProducts.GroupID)
INNER JOIN (tblDates INNER JOIN tblInventory ON tblDates.DateID = tblInventory.DateID) ON tblProducts.ProductID = tblInventory.ProductID
GROUP BY tblDates.DateID, tblProducts.GroupID;
I reckon I should basically have the same Query on a table different from tblInventory that would list all Products instead of listed products with 0 instead of no line but I am hesitant to do so as given the number of Dates and Products in my database, the query might be too slow.
There is probably a better way to achieve this.
Thanks
To get all possible Groups and Dates combinations, you'll have to CROSS JOIN those tables. Then you can LEFT JOIN to the other 2 tables:
SELECT
g.GroupID
, d.DateID
, COALESCE(SUM(i.Quantity), 0) AS Quantity
FROM
tblDates AS d
CROSS JOIN
tblGroups AS g
LEFT JOIN
tblProducts AS p
JOIN
tblInventory AS i
ON i.ProductID = p.ProductID
ON p.GroupID = g.GroupID
AND i.DateID = d.DateID
GROUP BY
g.GroupID
, d.DateID
use the isnull() function. change your query to:
SELECT tblDates.DateID, tblProducts.GroupID,
**ISNULL( Sum(tblInventory.Quantity),0)** AS SumOfQuantity
FROM (tblGroup INNER JOIN tblProducts ON tblGroup.GroupID = tblProducts.GroupID)
INNER JOIN (tblDates INNER JOIN tblInventory ON tblDates.DateID = tblInventory.DateID)
ON tblProducts.ProductID = tblInventory.ProductID
GROUP BY tblDates.DateID, tblProducts.GroupID;
You don't say which database you're using but what I'm familiar with is Oracle.
Obviously, if you inner join all tbales, you will not get the rows containing nulls. If you use an outer join to the inventory table you also have a problem because the groupid column is not listed in tblinventory and you can only outer join to one table.
I'd say you have two choices. Use a function or have a duplicate of the groupid column in the inventory table.
So, a nicer but slower solution:
create or replace
function totalquantity( d date, g varchar2 ) return number as
result number;
begin
select nvl(sum(quantity), 0 )
into result
from tblinventory i, tblproducts p
where i.productid = p.productid
and i.dateid = d
and p.groupid = g;
return result;
end;
select dateid, groupid, totalquantity( dateid, groupid )
from tbldates, tblgroups
Or, if you include the groupid column in the inventory table. (You can still quarantee integrity using constraints)
select d.dateid, i.groupid, nvl(i.quantity, 0)
from tbldates d, tblinventory i
where i.dateid(+) = d.dateid
group by d.dateid, g.groupid
Hope this helps,
GĂ­sli

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