2010-06-16 88 views
1

我使用的是SQL-SERVER 2005TSQL帮助与简单的查询

我有两个表,你可以在图中,CellularUsers和CellularPayments看到。我需要得到谁需要用户进行时,有一些规则收取:

  1. 如果用户ID的最后CellularPayments.paymentSum为8,然后选择所有 用户ID和userCellularNumbers其中 CellularPayments.date> GETDATE()
  2. 如果用户ID的最后CellularPayments.paymentSum为18然后选择所有 用户ID和userCellularNumbers其中 DATEADD(DD,7,CellularPayments.date)> GETDATE()

alt text http://img256.imageshack.us/img256/1946/63468037.png

预览图click here

我怎么做是正确的,现在但它不会吧?如果我正确地按照你的逻辑看起来我提前

回答

1

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) 

感谢,在where子句中应添加以下AND语句:

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

(我也让它成为内连接)

+0

好的!真的需要开始在这种情况下使用案例,嘿... – eugeneK 2010-06-17 06:18:47

+0

他们可以让惊人的灵活性。 (感谢他们的赞扬,他们将我带到了用户页面#42 [2010年6月17日],这应该是一个SO赢的条件!) – 2010-06-17 14:04:45