2013-11-20 70 views
1

我想在特定時間範圍內過濾出售的文件,但我仍然不知道如何在訂購論文時插入日期。請參閱現行規範使用count sql函數在特定時間內過濾項目

SELECT p.PaperID, p.PaperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders 
LEFT JOIN Papers as p 
ON Orders.PaperID=p.PaperID 
GROUP BY PaperName, p.PaperID 

Cuurent輸出:

PaperID   PaperName   No. of Orders 
1     Paper1    2 
2     Paper2    1 

數據庫表 銷售

SaleID    OrderID   Amount    Date 
1     1     10     2013-11-10 
2     2     10     2013-11-20 
3     3     30     2013-11-30 

訂單

OrderID   PaperID 
1     1 
2     1 
3     2 
+0

加入到銷售表之前和之前的分組添加:其中s.Date在'2013-11-10'和'2013-11-20'之間 – Zaki

+0

在查詢中向Sales表中添加另一個連接,使用它在WHERE子句中按日期進行篩選。 –

回答

1

試試這個:

SELECT p.PaperID, p.PaperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders 
LEFT JOIN Papers as p ON Orders.PaperID=p.PaperID 
LEFT JOIN Sales s ON s.orderid = orders.orderid 
Where s.Date Between '2013-11-10' AND '2013-11-20' 
GROUP BY PaperName, p.PaperID 
+0

當我嘗試上述查詢時,在LEFT JOIN中的Orders.OrderID銷售s ON s.OrderID = Orders.OrderID獲取錯誤「多部分標識符」Orders.OrderID「無法綁定」。 –

+0

@CharlesTan現在試試 – Zaki

+0

遇到不同的錯誤。 ON ON ON Orders.PaperID = p.PaperID得到錯誤「接近ON的錯誤語法」 –

1

在查詢中添加另一個JOINSales表。現在你有Sales.Date列,您可以在WHERE子句中使用它按日期過濾:

SELECT 
    p.PaperID, p.PaperName, COUNT(Orders.OrderID) AS NumberOfOrders 
    FROM Orders AS o 
LEFT JOIN Papers AS p ON o.PaperID = p.PaperID 
LEFT JOIN Sales AS s ON o.OrderID = s.OrderID 
WHERE s.Date BETWEEN '2013-1-1' AND '2013-12-31' 
GROUP BY PaperName, p.PaperID 

作爲選擇對象不JOIN(檢查什麼在你的情況下,具有最佳性能):

SELECT 
    p.PaperID, p.PaperName, COUNT(Orders.OrderID) AS NumberOfOrders 
    FROM Orders AS o 
LEFT JOIN Papers AS p ON o.PaperID = p.PaperID 
WHERE p.OrderID IN (
    SELECT OrderID FROM Sales WHERE Date BETWEEN '2013-1-1' AND '2013-12-31' 
) 
GROUP BY PaperName, p.PaperID 
+0

它只返回1行,應該是2行,因爲我有2個項目。 –

+0

請注意,我不相信使用[BETWEEN與這些日期](http://sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/what-do-between-and-the-devil-have-in -common.aspx),因爲我期望銷售表在將來使用時間戳... –

+0

我明白了。如果您不想使用BETWEEN,您會有什麼建議? –