【问题标题】:SQL working with dates in where clauseSQL 在 where 子句中处理日期
【发布时间】:2012-06-24 21:41:44
【问题描述】:

我这里有这个 SQL 代码..

SELECT cl.clientid,
       cl.clientname,
       cl.billingdate,
       cp.startdate,
       cp.expiration, 
       (SELECT COUNT(*)
            FROM invoice 
            HERE client = cl.clientid) AS invoicecount  
FROM client cl
INNER JOIN clientplan cp ON cp.client = cl.clientid
WHERE cl.isbilled = 1 AND expiration is NULL AND expiration > '2012-06-22'

我的问题是一个客户可能有 3 个客户计划,它们要么有一个到期日期,要么到期为 NULL。我正在尝试获取未过期或为 NULL 的行。

我做错了什么?

【问题讨论】:

  • 如果日期为 NULL,您将永远不会有一个值。edit 所以它要么是 EXPIRATION IS NULL 要么 (EXPIRATION IS NOT NULL AND EXPIRATION > '22-JUN-2012') [/编辑]
  • AND 并不意味着 these records and those records 它意味着 where this is true and that is true。在您的情况下,您不能让expiration IS NULL 和 expiration > '2012-06-22' 同时为真。你的意思是cl.isbilled = 1 AND (expiration is NULL OR expiration > '2012-06-22')
  • 作为旁注,它可能值得添加到今天日期的 sql 实现版本中。例如在 postgres 中它的 now()

标签: sql inner-join where


【解决方案1】:

我不确定,但这不是你想要的:

SELECT cl.clientid, cl.clientname, cl.billingdate, cp.startdate, cp.expiration, 
(select count(*) from invoice where client = cl.clientid) as invoicecount  
FROM client cl
inner join clientplan cp on cp.client = cl.clientid
where cl.isbilled = 1 and (expiration is NULL or expiration > '2012-06-22')

到期时用 or 代替 and。因为过期不能为空且 > '2012-06-22'...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多