View Single Post

   
  #3 (permalink)  
Old 02-29-2008, 02:23 AM
Kevin Frey
 
Posts: n/a
Default Re: SQL Statement for generating expired customer

My first comment is that based on what you have described, the Invoice
table is redundant and should be combined with the Invoice Details
tables.

I post some [rough] DDL below:

create table Customer
(
C_Code varchar( 10 ),
C_Name varchar( 30 ) not null,
)

create table Invoice
(
C_Invoice_No varchar( 10 ) not null,
C_Customer_Code varchar( 10 ) not null,
C_Commences datetime not null,
C_Expires datetime not null,
C_Amount int
)

insert Customer( C_Code, C_Name ) values ( '001', 'Kevin' )
insert Customer( C_Code, C_Name ) values ( '002', 'Paul' )
insert Customer( C_Code, C_Name ) values ( '003', 'Roger' )

insert Invoice( C_Invoice_No, C_Customer_Code, C_Commences, C_Expires
)
values ( '1', '001', '01-March-2004', '31-March-2004' )
insert Invoice( C_Invoice_No, C_Customer_Code, C_Commences, C_Expires
)
values ( '2', '002', '01-March-2004', '31-March-2004' )
insert Invoice( C_Invoice_No, C_Customer_Code, C_Commences, C_Expires
)
values ( '3', '003', '01-February-2004', '28-February-2004' )

The query below assumes that:

a. The billing period is the same for all customers. That is, everyone
is billed from 1st of month to 31st (or last day) of the month. The
SQL below won't work unless this fact holds true.
b. The billing period has no breaks in it. That is, if the last day of
a billing period is 31st March, the commence date of the next period
is 1st April, not 2nd April etc.

select * from Customer
where C_Code in (
select distinct C_Customer_Code from Invoice
group by C_Customer_Code
having max( C_Expires ) = dateadd( dd, -1, '01-April-2004' )
)

Effectively '01-April-2004' is the date of your next "Commence" period
so this query simply looks for customers having an invoice with an
expiry date which matches the expiry date of the previous billing
period.

At the end of the day, however, you can vary the having clause to get
the type of result you need.
Reply With Quote