2017-04-03 78 views
1

我正在創建一個從多個表中選擇數據的查詢。我已完成所有查詢,但現在必須將WHERE子句應用於整個查詢。 我有9選擇語句,這些工作正常。數據正在從不同的表中選擇。現在我想聲明日期session,我希望根據提供的日期過濾所有數據。我使用下面的查詢:如何將WHERE子句應用於SQL Server中的多個SELECT語句

SELECT 
    (SELECT COUNT(DISTINCT OrderItems.ProductID) 
    FROM OrderItems) AS 'TotalSoldItemsDistinct', 
    (SELECT COUNT(OrderItems.ProductID) 
    FROM OrderItems) AS 'TotalSoldItemsInDistinct', 
    (SELECT COUNT(Orders.OrderID) 
    FROM Orders) AS 'TotalOrders', 
    (SELECT COUNT(Orders.OrderID) 
    FROM Orders 
    WHERE Orders.OrderStatusID = @CompleteOStatusID) AS 'CompleteOrders', 
    (SELECT COUNT(Orders.OrderID) 
    FROM Orders 
    WHERE Orders.OrderStatusID = @PendingOStatusID) AS 'PendingOrders', 
    (SELECT COUNT(Orders.ClientID) 
    FROM Orders 
    WHERE Orders.ClientID != @WalkingCustID) AS 'namedcustomers', 
    (SELECT COUNT(Orders.ClientID) 
    FROM Orders 
    WHERE Orders.ClientID = @WalkingCustID) AS 'WalkingCustomers', 
    (SELECT SUM(OrderItems.PurchasePrice) 
    FROM OrderItems) AS 'TotalPurchasePrice', 
    (SELECT SUM(OrderItems.SalePrice) 
    FROM OrderItems) AS 'TotalSalePrice' 

我選擇從2個表數據名爲「Orders」和「OrderItems」,我有「訂單」表和列OrderDateTransactionDateOrderItems表上,我想使用過濾器。任何人都可以建議如何應用過濾器到整個查詢?

+0

還有比這裏解決您的問題..你的查詢可以更簡化 – maSTAShuFu

+0

感謝回覆更多。將ü請建議我該怎麼做? –

+0

你將不得不尋找一個類似的情況下,或等到有人,因爲我現在要回家:) – maSTAShuFu

回答

0

這並不完全清楚你想要什麼結果,但在這裏有兩種方法。

  1. 嘗試在同一時間選擇從2個表數據下面(與標準替換日期):

    SELECT * FROM Orders AS o INNER JOIN OrderItems AS i WHERE o.TransactionDate = '2015-02-12' AND i.OrderDate = '2015-02-12';

SELECT *從兩個表爲選擇所有列一個結果和WHERE ... AND ... - 條款篩選結果只有您定義的日期。

  1. 請嘗試以下操作,以僅爲與特定訂單上的日期匹配的數據選擇訂單商品數據。

    SELECT i.* FROM Orders AS o INNER JOIN OrderItems AS i WHERE o.TransactionDate = i.OrderDate AND o.OrderID = '12345';

SELECT i.*告訴查詢只返回的OrderItems的列。並且WHERE o.TransactionDate = i.OrderDate確保只返回OrderID爲「12345」的訂單的同一日期的訂單項(這是用AND o.OrderID = '12345'定義的。因爲您的訂單表上有一個「OrderID」字段,所以這樣做會起作用,並且您希望使用它作爲一個標準。

1

你可以試試這個

;with tempOrderItems AS 
    ( 
     SELECT 
     COUNT(DISTINCT OrderItems.ProductID) AS 'TotalSoldItemsDistinct', 
     COUNT(OrderItems.ProductID) AS 'TotalSoldItemsInDistinct', 
     SUM(OrderItems.PurchasePrice) AS 'TotalPurchasePrice', 
     SUM(OrderItems.SalePrice) AS 'TotalSalePrice' 
     FROM OrderItems ori 
     WHERE OrderDate BETWEEN xxx AND yyy 
    ) 
, tempOrders AS 
    (
     SELECT 
     COUNT(o.OrderID) AS 'TotalOrders', 
     SUM(CASE WHEN o.OrderStatusID = @CompleteOStatusID THEN 1 ELSE 0 END) AS 'CompleteOrders', 
     SUM(CASE WHEN o.OrderStatusID = @PendingOStatusID THEN 1 ELSE 0 END) AS 'PendingOrders', 
     SUM(CASE WHEN o.ClientID != @WalkingCustID THEN 1 ELSE 0 END) AS 'namedcustomers', 
     SUM(CASE WHEN o.ClientID = @WalkingCustID THEN 1 ELSE 0 END) AS 'WalkingCustomers' 
     FROM Orders o 
     WHERE TransactionDate BETWEEN xxx AND yyy 

    ) 
SELECT * FROM tempOrderItems 
CROSS JOIN tempOrders 
相關問題