SQL服务器总和和计数

时间:2015-08-03 12:46:34

标签: sql sql-server tsql join

我有两张桌子:

订单:

  1. 订单ID
  2. 的OrderTotal
  3. 状态
  4. orderStatesHistory

    1. ID
    2. 订单ID
    3. STATEID
    4. 我需要显示get来显示这样的结果。

      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()"中使用每个orderId一次。和" sum()"

      我一直在努力奋斗,不确定我是否能用SQL完成所有工作,也许有些天才帮助我,如果不是我会通过软件完成。

      注意:当我执行count()和sum()时,我想每次orderId只使用一次,如果它们是重复的,我不想计算它们。

      任何帮助都是有帮助的,甚至有人说这是不可能的。

      PD:如果需要,我愿意使用JOINS,不需要使用SQL服务器专用语言。

      更新1:

      orderStatesHistory中的数据 enter image description here

      订单中的数据 enter image description here

1 个答案:

答案 0 :(得分: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