【问题标题】:SQL sum over(partition) not subtracting negative values in SUMSQL sum over(partition) 不减去 SUM 中的负值
【发布时间】:2018-08-07 11:36:26
【问题描述】:

我有以下查询,它输出每个用户的交易列表 - 花费的单位和获得的单位 - 列“金额”。

我已设法将每个用户分组并计算出运行总计 - 列“Running_Total_Spend”。

但是,它是添加负“数量”值而不是减去它们。 Sp 很确定这是查询的 SUM 部分不起作用。

WITH cohort AS(
    SELECT DISTINCT userID FROM events_live WHERE startDate = '2018-07-26' LIMIT 50),

    my_events AS (
    SELET events_live.* FROM events_live WHERE eventDate >= '2018-07-26')

    SELECT cohort.userID,
    my_events.eventDate, 
    my_events.eventTimestamp, 
    CASE
--spent resource outputs a negative value ---working
    WHEN transactionVector = 'SPENT' THEN -abs(my_events.productAmount)

--earned resource outputs a positive value ---working
    WHEN transactionVector = 'RECEIVED' THEN  my_events.productAmount END AS Amount,
    ROW_NUMBER() OVER (PARTITION BY cohort.userID ORDER BY cohort.userID, eventTimestamp asc) AS row,
--sum the values in column 'Amount' for this partition
--should sum positive and negative values ---NOT WORKING--converting negatives into positive
--------------------------------------------------
    SUM(CASE WHEN my_events.productAmount >= 0 THEN my_events.productAmount
    WHEN my_events.productAmount <0 THEN -abs(my_events.productAmount) end) OVER(PARTITION BY cohort.userID ORDER BY cohort.userID, eventTimestamp asc) AS Running_Total_Spend
---------------------------------------------------
    FROM cohort
    INNER JOIN my_events ON cohort.userID=my_events.userID
    WHERE   productName = 'COINS' AND transactionVector IN ('SPENT','RECEIVED')

【问题讨论】:

  • 我认为abs 函数导致了这里的错误。
  • 尝试将其更改为 -1*(my_events.productAmount) - 仍然无法正确求和
  • 我不知道您为什么还要对 Sum 函数使用大小写。 SQL 将处理负数。在 sum 函数中去掉 Case。

标签: sql


【解决方案1】:

我怀疑您也希望围绕 transactionvector 的逻辑求和,因为 my_events.productamount 似乎总是积极的。

...
sum(CASE
      WHEN transactionvector = 'SPENT' THEN
        -my_events.productamount
      WHEN transactionvector = 'RECEIVED' THEN
        my_events.productamount
    END) OVER (PARTITION BY cohort.userid
               ORDER BY cohort.userid,
                        eventTimestamp) running_total_spend
...

【讨论】:

    【解决方案2】:

    将 sum 函数更新为 -

    SUM(my_events.productAmount) OVER(PARTITION BY cohort.userID ORDER BY cohort.userID, eventTimestamp asc) AS Running_Total_Spend
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 2020-01-14
      相关资源
      最近更新 更多