【发布时间】: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