2014-06-14 51 views
1

我有兩個表...SQL GROUP BY和骨料需要幫助

  • 訂單(訂單編號,orderDate存儲,發貨日期,requiredDate,狀態customerNumber之)和
  • 訂單明細(訂單編號,產品代碼,quantityOrdered,priceEach ,orderLineNumber)

我試圖返回這樣的查詢...

+----------------------------------+--------------------+ 
| DATEDIFF(shippedDate, orderDate) | COUNT(shippedDate) | 
+----------------------------------+--------------------+ 
|        1 |     50 | 
|        2 |     49 | 
|        3 |     52 | 
|        4 |     52 | 
|        5 |     59 | 
|        6 |     45 | 
|        7 |     2 | 
|        8 |     2 | 
|        65 |     1 | 
+----------------------------------+--------------------+ 

但我只是沒有得到它。我知道我必須做1組,並使用則DateDiff()和COUNT()...

我已經試過這一點,但它不是正確的 的mysql:

select DATEDIFF(shippedDate,orderDate), COUNT(shippedDate) from Orders Group by shippedDate; 

有什麼建議?

+0

刪除了SQL Server的標記,因爲問題明確地說: 「MySQL的」 組添加DATEDIFF(發貨日期,orderDate存儲) 。 –

回答

1

您需要group bydatediff()

select DATEDIFF(shippedDate, orderDate), COUNT(shippedDate) 
from Orders 
Group by DATEDIFF(shippedDate, orderDate); 
+0

謝謝!如果我想刪除NULL值,該怎麼辦? – CoderRightInTheProgram

+0

@ dognose。 。 。 (1)SQL標籤通常與其他數據庫結合使用。其目的似乎是爲了擴大觀衆。 (2)這在SQL Server中不起作用,因爲'datediff()'在SQL Server中有三個參數。 (3)我不確定你在說什麼。對於'datediff()'的第三個參數,這將在SQL Server中起作用。 –

+0

@ user3740517。 。 。你可以添加'where shippedDate不爲null並且orderDate不爲空'或者可能用'coalesce()'用'now()'替換NULL值。 –

1

您需要通過聲明,而不是發貨日期