I have a client who has four invoices. eg
client# amtpd ttlorder BeginDt EndDt 1 200.00 4 5/1/01 5/3/01 1 150.00 2 5/4/01 5/7/01 1 50.00 7 5/7/01 5/15/01 1 600.00 10 6/1/01 6/15/01
I would like to combine first three records and display the report to read
1 400.00 13 5/1/01 5/15/01 1 600.00 10 6/1/01 6/15/01
Looks like you are producing totals based on month. You need to use the GROUP BY clause in order to get monthly totals, and you will have to extract the month out of each invoice in order to include the invoice in the correct group. Note that if the month of BeginDt is not the same as the month of EndDt, the following will not work ("results are unpredictable") and something more complex will be required.
select client , month(BeginDt) , sum(amtpd) , sum(ttlorder) , min(BeginDt) , max(EndDt) from invoices group by client , month(BeginDt)
Note that not every database will let you do a GROUP BY on a function. In that case, you need to declare a view first --
create view monthinvoices ( client , invoicemonth , amtpd , ttlorder , BeginDt , EndDt ) as select client , month(BeginDt) , amtpd , ttlorder , BeginDt , EndDt from invoices
Then the query on the view looks like this --
select client , invoicemonth , sum(amtpd) , sum(ttlorder) , min(BeginDt) , max(EndDt) from monthinvoices group by client , invoicemonth
For More Information
- What do you think about this answer? E-mail the Edtior at email@example.com with your feedback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have a SQL tip to offer your fellow DBA's and developers? The best tips submitted will receive a cool prize--submit your tip today!
- Ask your technical SQL questions--or help out your peers by answering them--in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, and data warehousing gurus are waiting to answer your toughest questions.
This was first published in November 2001