SQL总销售额计算

时间:2013-01-04 18:05:19

标签: sql sql-server sql-server-2008 sum

我有一张促销表,包括购买/退货/换货 样品:

--------**saleTbl**------------
CustID | DOP | SKU | Price
111 | 11/05/12 | 001 | 45.99
222 | 11/20/12 | 001 | 45.99
111 | 11/06/12 | 002 | 40.95
111 | 11/06/12 | 001 | -45.99
111 | 11/19/12 | 004 | 50.00
222 | 11/25/12 | 003 | 20.99
111 | 12/01/12 | 002 | -40.95
111 | 12/01/12 | 003 | 20.99

标准是:在2012年5月11日至2012年11月11日期间找到每位客户的总数。如果客户交换了在此期间购买的商品,并且在同一天购买将被计算在内。 预期结果是:

CustID | DOP | Price
222 | 11/20/12 | 45.99
111 | 12/01/12 | 70.99

我试图获得总数,但当然不对:

SELECT DISTINCT [num_cp] AS 'Member Id'
      ,MAX([dop]) AS 'Date'
      ,SUM([price]) AS 'Point'
  FROM [Mailing_List].[dbo].[UGG_DoublePoint]
  WHERE [num_cp] IN
  (
    SELECT [num_cp]
    FROM [Mailing_List].[dbo].[UGG_DoublePoint]
    GROUP BY [num_cp]
    HAVING SUM([price]) >0
  )
  --AND 
  AND [dop] BETWEEN '11/05/12' AND '11/20/12'
  GROUP BY [num_cp]

请帮忙!谢谢大家。

2 个答案:

答案 0 :(得分:1)

我认为您需要将查询更改为此

; WITH CTE AS 
(
    SELECT *, 
    COUNT(*) OVER (PARTITION BY CustID, DOP) Row_Cnt
    FROM TEST
), CTE2 AS 
(
    SELECT * FROM CTE
    WHERE [dop] BETWEEN '11/05/12' AND '11/20/12'
), CTE3 AS 
(
    SELECT * FROM CTE2 WHERE price > 0
    UNION
    SELECT * FROM CTE2 WHERE price < 0 
    and SKU IN (SELECT SKU FROM CTE2 WHERE Price > 0)
    UNION
    SELECT * FROM CTE
    WHERE row_cnt > 1 and DOP IN (
    SELECT max(A.dop) d FROM CTE A
    INNER JOIN CTE2 B ON A.CustID = B.CustID AND A.SKU = B.SKU
    )
 )
SELECT Custid, max(dop) dateid, sum(price) Price
from cte3
group by custid;

检查SQL Fiddle Demo

答案 1 :(得分:0)

我认为这会奏效。它基本上通过使用左连接过滤掉结果集中的任何返回。

注意:如果有人在同一天购买/退回同一件商品的多个SKU,则会出现此问题。

select pur.CustId, sum(pur.price) TotalPrice
from test pur
left join test ret
  on pur.custid = ret.custid
   and pur.dop = ret.dop
   and pur.sku = ret.sku
   and pur.price = (-1 * ret.price)
where pur.dop between '11/05/2012' AND '11/20/2012'
  and ret.price is null
group by  pur.CustId