2013-06-22 101 views
1

我有一個表ORDERS,有一個字段DATE_ADD,日期格式爲2010-02-28 20:48:09。我需要找出沒有訂單的日期。我試過SQL:查找日期無記錄

SELECT * FROM `orders` HAVING COUNT(date_add) < 1 

但它返回0結果雖然必須有一些。在這個查詢中我在哪裏錯了?

+0

'HAVING'是'GROUP BY'的合作伙伴。嘗試一起使用它們 – Raptor

+0

你有多少場?..我的意思是列? – Ahmed

回答

1

試試這個:

SELECT DATE(date_add), COUNT(date_add) AS cnt FROM `orders` GROUP BY DATE(date_add) HAVING COUNT(date_add) < 1 
0

您無法查詢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