views:

43

answers:

1

I'm using SQL-SERVER 2005.

I have two tables as you can see on diagram, CellularUsers and CellularPayments. I need to get users who needs to be charged when there are few rules:

  1. if last CellularPayments.paymentSum of userID was 8 then select all userID and userCellularNumbers where CellularPayments.date>getdate()
  2. if last CellularPayments.paymentSum of userID was 18 then select all userID and userCellularNumbers where dateadd(dd,7,CellularPayments.date)>getdate()

alt text

to preview diagram click here

how i do it right now but it doesn't looks right to me

select cu.userID,cu.userCellularNumber from CellularUsers cu
left join CellularPayments cp
on cu.userID=cp.userID
where cu.isPaymentRecurring=1
and isActivated=1
and cp.paymentID in (select max(paymentID) from CellularPayments group by userID)

thanks in advance

+1  A: 

If I'm following your logic correctly, adding the following AND statement to the where clause should do it:

and dateadd( dd
            ,case cp.PaymentSum
               when 8 then 0
               when 18 then 7
               else [AppropriateDefaultValue]
             end
            ,CellularPayments.date) > getdate()

(I'd also make it an inner join.)

Philip Kelley
@Philip Kelley, Good one ! Really need to start using cases in such cases, heh...
eugeneK
They can allow amazing flexiblility. (And thanks for the upvotes, they landed me on User Page #42 [Jun 17 2010]. That's got to be an SO win condition!)
Philip Kelley