SELECT date_trunc('month', dateordered), SUM(orders) - (
SELECT SUM(orders)
FROM c_orders
WHERE orderstatus = 'returned'
)
FROM c_orders
WHERE orderstatus = 'complete'
GROUP BY 1
这给了我以下输出:
date_trunc total_orders
2016-08-01 00:00:00 129
2016-09-01 00:00:00 125
2016-10-01 00:00:00 160
2016-11-01 00:00:00 202
2016-12-01 00:00:00 357
我想从八月开始计算逐月变化的百分比。我怎么能在我的SQL查询中做到这一点?
TIA
答案 0 :(得分:1)
为什么使用该查询?这更简单:
SELECT date_trunc('month', dateordered) as yyyymm,
SUM(CASE WHEN orderstatus = 'returned' THEN orders
WHEN orderstatus = 'complete' THEN - orders
ELSE 0
END) as net
FROM c_orders
GROUP BY yyyymm
ORDER BY yyyymm;
然后使用lag()
:
WITH o as (
SELECT date_trunc('month', dateordered) as yyyymm,
SUM(CASE WHEN orderstatus = 'returned' THEN orders
WHEN orderstatus = 'complete' THEN - orders
ELSE 0
END) as net
FROM c_orders o
GROUP BY yyyymm
)
SELECT o.*,
(net / LAG(net) OVER (ORDER BY yyyymm) - 1) as net_change
FROM o
ORDER BY yyyymm;
要获取2016-08以来的数据,您需要更多级别的子查询:
SELECT o.*
FROM (SELECT o.*,
(net / LAG(net) OVER (ORDER BY yyyymm) - 1) as net_change
FROM o
) o
WHERE yyyymm >= '2016-08-01'
ORDER BY yyyymm;
答案 1 :(得分:0)
您可以使用LAG()从上一行中选择total_orders
进行百分比计算
with total_orders(date_trunc,total_orders) as (
values
('2016-08-01 00:00:00' ,129)
,('2016-09-01 00:00:00' ,125)
,('2016-10-01 00:00:00' ,160)
,('2016-11-01 00:00:00' ,202)
,('2016-12-01 00:00:00' ,357)
)
,with_base as (select *,(lag(total_orders,1,0) over (ORDER BY date_trunc))
from total_orders)
select date_trunc
, total_orders
, (case when 0 = lag
then 0
else total_orders / lag::FLOAT * 100 end)::INT as percent
from with_base;
结果:
date_trunc total_orders percent
"2016-08-01 00:00:00",129 ,0
"2016-09-01 00:00:00",125 ,97
"2016-10-01 00:00:00",160 ,128
"2016-11-01 00:00:00",202 ,126
"2016-12-01 00:00:00",357 ,177