2015-08-03 73 views
0

我有兩個表:SQL服務器之和計算

訂單:

  1. 訂單ID
  2. 的OrderTotal
  3. 狀態

orderStatesHistory

  1. 訂單ID
  2. STATEID

我需要顯示得到顯示這樣的結果。

enter image description here

現在我的代碼是這樣的,我使用的SQL Server

WITH totalOrders AS 
 
    (
 
    SELECT orders.state, COUNT(1) AS counter, SUM(orders.orderTotal) AS total 
 
    FROM orders 
 
    CROSS APPLY 
 
    (
 
     SELECT orderId, currentDateTime FROM orderStatesHistory 
 
     WHERE (orderStatesHistory.stateId = 1 OR orderStatesHistory.stateId = 3) 
 
     AND NULLIF(orderStatesHistory.subStateId, 0) IS NULL 
 
     AND orderStatesHistory.currentDateTime BETWEEN '2015-07-28 00:00:00' AND '2015-08-04 00:00:00'  
 
     AND orders.id = orderStatesHistory.orderId 
 
    ) AS statesHistory 
 
    WHERE orders.state IN (1,2,3,4,5) 
 
    AND orders.documentType = 1 
 
    GROUP BY orders.state 
 
) 
 
    SELECT 9999 AS state, SUM(counter) AS counter, SUM(total) AS total 
 
    FROM totalOrders 
 

 
    UNION 
 
    
 
    SELECT state, counter, total 
 
    FROM totalOrders

問題是不知何故,在orderStatesHistory登記可能會被複制,而我只想要在「count()」和「sum()」中使用每個orderId一次

我一直在努力非常難,不知道我是否可以用SQL來完成這一切,也許有些天才能幫助我,如果不是,我會通過軟件來完成。注意:當我執行count()和sum()時,我只想使用一次每個orderId,如果它們重複,我不想對它們進行計數。

任何幫助都是有好處的,甚至有人說這是不可能的。

PD:如果需要,我願意使用JOINS,不需要使用SQL Server特定的語言。

更新1:

數據在orderStatesHistory enter image description here

數據訂單 enter image description here

回答

0

您應該能夠使用來實現這個JOINDISTINCT代替CROSS APPLY。如果您可以發佈一些示例數據,這將有助於驗證。

WITH totalOrders AS 
 
    (
 
    SELECT orders.state, COUNT(1) AS counter, SUM(orders.orderTotal) AS total 
 
    FROM orders 
 
    INNER JOIN 
 
    (
 
     SELECT DISTINCT orderId FROM orderStatesHistory 
 
     WHERE (orderStatesHistory.stateId = 1 OR orderStatesHistory.stateId = 3) 
 
     AND NULLIF(orderStatesHistory.subStateId, 0) IS NULL 
 
     AND orderStatesHistory.currentDateTime BETWEEN '2015-07-28 00:00:00' AND '2015-08-04 00:00:00' 
 
    ) AS statesHistory 
 
    ON orders.id = statesHistory.orderId 
 
    WHERE orders.state IN (1,2,3,4,5) 
 
    AND orders.documentType = 1 
 
    GROUP BY orders.state 
 
) 
 
    SELECT 9999 AS state, SUM(counter) AS counter, SUM(total) AS total 
 
    FROM totalOrders 
 

 
    UNION 
 
    
 
    SELECT state, counter, total 
 
    FROM totalOrders

+0

不,還是一樣,我的查詢必須從表中orderStatesHistory通過STATEID組,然後計數(1)和(的OrderTotal)從訂單表只用diferent orderId的註冊表。 無論如何謝謝 – Borjante

+0

如果你可以編寫一些樣本數據的腳本,這將幫助我更快地調試一下。 – TTeeple

+1

@Borjante查看更新的答案。從子查詢中取出currentDateTime,因爲它不在外部查詢中使用。 – TTeeple