SQL总和(分区)不减去SUM中的负值

时间:2018-08-07 11:36:27

标签: sql

我有以下查询,该查询输出每个用户的交易列表-支出单位和收入单位-“金额”列。

我设法将每个用户对此分组,并进行总计-“ 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')

2 个答案:

答案 0 :(得分:0)

我怀疑您也希望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
...

答案 1 :(得分:0)

将求和函数更新为-

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