4

我有一张销售表,包括购买/退货/换货示例:

--------**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 年 11 月 5 日至 2012 年 11 月 20 日期间找到每个客户的总数。如果客户交换了在此期间购买的商品并且在同一天购买的商品将被计算在内。预期结果是:

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]

请帮忙!谢谢大家。

4

2 回答 2

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 演示

于 2013-01-04T18:13:08.243 回答
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
于 2013-01-04T19:39:49.307 回答