【问题标题】:TSQL Help with simple query简单查询的 TSQL 帮助
【发布时间】:2010-06-17 00:08:38
【问题描述】:

我使用的是 SQL-SERVER 2005。

如图所示,我有两张表,CellularUsers 和 CellularPayments。我需要在规则很少的情况下获取需要收费的用户:

  1. 如果最后一个 CellularPayments.paymentSum of userID 为 8,则选择所有 userID 和 userCellularNumbers 其中 CellularPayments.date>getdate()
  2. 如果最后一个 CellularPayments.paymentSum of userID 为 18,则选择所有 userID 和 userCellularNumbers 其中 dateadd(dd,7,CellularPayments.date)>getdate()

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

预览图click here

我现在是怎么做的,但我觉得不合适

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)

提前致谢

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

    如果我正确地遵循了您的逻辑,则应将以下 AND 语句添加到 where 子句:

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

    (我也将其设为内部连接。)

    【讨论】:

    • 它们可以带来惊人的灵活性。 (感谢您的支持,他们让我进入了用户页面 #42 [2010 年 6 月 17 日]。这一定是一个如此获胜的条件!)
    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多