views:

43

answers:

1

What is the best approach to display the summery of DETAILED.Fields in its master table?

E.g. I have a master table called 'BILL' with all the bill related data and a detailed table ('BILL_DETAIL') with the bill detailed related data, like NAME, PRICE, TAX, ... Now I want to list all BILLS, without the details, but with the sum of the PRICE and TAX stored in the detail table.

Here is a simplified schema of that tables:

TABLE BILL
----------
- ID
- NAME
- ADDRESS
- ...

TABLE BILL_DETAIL
-----------------
- ID
- BILLID
- PORDUCT_NAME
- PRICE
- TAX
- ...

The retrieved table row should look like this:

BILL.CUSTOMER_NAME, BILL.CUSTOMER_ADDRESS, sum(BILL_DETAIL.PRICE), sum(BILL.DETAIL.TAX), ...

Any sugguestions?

A: 

A simple GROUP BY and a LEFT JOIN should get you what you want:

Select
  bill.customer_name,
  bill.customer_address,
  Sum(bill_detail.price),
  Sum(bill_detail.tax)
From bill
Left Join bill_detail On ( bill_detail.billid = bill.id )
Group By bill.id, bill.customer_name, bill.customer_address

Make sure to group by all columns of table bill that you have in the column list of your select.

Peter Lang
The problem is, that my BILL table has a lot fields, and it has also some more detailed tables, with other fields I want to sum up. I aleady use some other joins, too. It's actually a big SELECT query. Not sure how fast GROUP BY is. I also thought using VIEWS to sum up all my detailed tables and then join it?
max
I would not expect you to have any performance problems caused by the `GROUP BY`, but you will have to try for yourself. The view could improve readability, but again, you will have to try how it performs with your model.
Peter Lang
write it out. views are almost always not a benefit
Randy