我有一个表ORDERS
,有一个字段DATE_ADD
,日期格式是2010-02-28 20:48:09
。我需要找出没有订单的日期。我试过了
SELECT * FROM `orders` HAVING COUNT(date_add) < 1
但它返回 0 结果虽然必须有一些。我在这个查询中哪里错了?
尝试这个:
SELECT DATE(date_add), COUNT(date_add) AS cnt FROM `orders` GROUP BY DATE(date_add) HAVING COUNT(date_add) < 1
您无法查询orders
表中不包含的数据。或者,换一种说法,您需要一个包含所有可用日期的表格。如果您有一个日历表,那么您可以执行以下查询:
select c.*
from calendar c left outer join
(select distinct cast(date_add as date) as date_add
from orders
) o
on c.date = o.date_add
where o.date_add is null
注意:您需要转换date_add
为日期(删除时间部分)。这因数据库而异。以上是 SQL Server 语法。它也可能是date(date_add)
(MySQL)或trunc(date_add)
(Oracle)之类的东西或其他东西。
如果您没有日历表,那么创建一个非常特定于数据库的表。如果几乎所有日期都有订单,你可以这样做:
select driver.dte
from (select dte
from (select distinct cast(date_added + n.n as date) as dte
from orders
) o cross join
(select 0 as n union all select 1 as n union all select 2 as n
)
) driver left outer join
(select distinct cast(date_add as date) as date_add
from orders
) o
on driver.dte = o.date_add
where o.date_add is null