我正在尝试从时间记录表中为用户事务整理一些数据。这是一个简单的数据表,其中包含日期和销售完成或放弃的指标..
这是一些数据
UserId TimeStamp MonthName Code Cost
1 01/01/2018 January SALE_COMPLETE 115.00
1 02/01/2018 January SALE_COMPLETE 199.00
1 03/01/2018 January SALE_COMPLETE 177.00
1 12/01/2018 January SALE_ABANDONED 103.00
1 13/01/2018 January SALE_ABANDONED 126.00
1 14/01/2018 January SALE_ABANDONED 31.00
2 15/01/2018 January SALE_ABANDONED 141.00
2 16/01/2018 January SALE_ABANDONED 169.00
2 17/01/2018 January SALE_ABANDONED 216.00
2 18/01/2018 January SALE_ABANDONED 186.00
2 19/01/2018 January SALE_ABANDONED 239.00
2 20/01/2018 January SALE_ABANDONED 144.00
2 21/01/2018 January SALE_ABANDONED 160.00
2 22/01/2018 January SALE_ABANDONED 121.00
2 23/01/2018 January SALE_ABANDONED 168.00
2 24/01/2018 January SALE_ABANDONED 78.00
2 25/01/2018 January SALE_ABANDONED 160.00
2 26/01/2018 January SALE_ABANDONED 11.00
2 27/01/2018 January SALE_ABANDONED 128.00
2 28/01/2018 January SALE_ABANDONED 191.00
2 29/01/2018 January SALE_ABANDONED 232.00
2 30/01/2018 January SALE_ABANDONED 201.00
2 31/01/2018 January SALE_ABANDONED 109.00
2 01/02/2018 February SALE_ABANDONED 160.00
2 02/02/2018 February SALE_ABANDONED 103.00
2 03/02/2018 February SALE_ABANDONED 146.00
2 04/02/2018 February SALE_ABANDONED 22.00
2 05/02/2018 February SALE_ABANDONED 74.00
2 06/02/2018 February SALE_ABANDONED 102.00
2 07/02/2018 February SALE_ABANDONED 66.00
2 08/02/2018 February SALE_ABANDONED 118.00
我想要做的是在代码为SALE_ABANDONED并且代码大于或等于5个实例或每个用户的总费用>少于5个实例。最后将这几个月分组。
所以这就是我要回归的内容
MonthName >=5 CostLoss <5 CostLoss
January 2654 260
February 791 0
请注意,2月份UserId 2仍然符合&gt; = 5类别,因为它继续从1月份的SALE_ABANDONED实例开始。
我希望这对某人真的有意义,我知道它非常棘手......
答案 0 :(得分:0)
您需要嵌套的agregation,一个简单的计数加上条件聚合:
select MonthName,
-- split the counts in two groups, ">=" and "<"
sum(case when cnt >= 5 then sumCost else 0 end) as ">=5 CostLoss",
sum(case when cnt < 5 then sumCost else 0 end) as "<5 CostLoss"
from
( -- number of abandoned sales per user/month
select UserId, MonthName,
sum(cost) as sumCost,
count(*) as cnt
from myTable
where Code = 'SALE_ABANDONED'
group by UserId, MonthName
) as dt
group by MonthName
答案 1 :(得分:0)
这将获得每月成本的总和,然后总结所有低于5和大于5的成本损失。
select MonthName,
sum(case when cnt >= 5 then sum_cost else 0 end) as ">=5 CostLoss",
sum(case when cnt < 5 then sum_cost else 0 end) as "<5 CostLoss"
from
( select UserId,
month(TStamp) as monthNum,
MonthName,
sum(Cost) as sum_cost,
count(*) as cnt
from yourTable
where Code = 'SALE_ABANDONED'
group by UserId, month(TStamp), MonthName
) as t
group by MonthName
order by monthNum
Result:
MonthName >=5 CostLoss <5 CostLoss
January 2654 260
February 791 0