像这样的东西可能是你正在寻找的东西。这将计算每个组合从“有货”到“缺货”的次数,item
反之亦然location
。请注意,每个item
and的第一行location
不能算作转换,因为我们不知道给定此逻辑的先前状态。
SELECT item,
location,
SUM( CASE WHEN status = 'In Stock' AND prior_status = 'Out of Stock'
THEN 1
ELSE 0
END) moved_to_out_of_stock,
SUM( CASE WHEN status = 'Out of Stock' AND prior_status = 'In Stock'
THEN 1
ELSE 0
END) moved_to_in_stock
FROM (SELECT item,
location,
status,
lag( status ) over (partition by item, location
order by dt) prior_status
FROM (SELECT item,
location,
(case when inventory <= 0
then 'Out of Stock'
else 'In Stock'
end) status,
dt
FROM your_table))
GROUP BY item, location
这表明在您发布的示例数据中,该项目一次从缺货变为有货,并从有货变为缺货一次。
SQL> ed
Wrote file afiedt.buf
1 with your_table as (
2 select 1243 item, 10 location, 2 inventory, date '2012-03-12' dt from dual union all
3 select 1243, 10, 0, date '2012-03-13' from dual union all
4 select 1243, 10, -2, date '2012-03-14' from dual union all
5 select 1243, 10, -2, date '2012-03-15' from dual union all
6 select 1243, 10, 4, date '2012-03-16' from dual
7 )
8 SELECT item,
9 location,
10 SUM( CASE WHEN status = 'In Stock' AND prior_status = 'Out of Stock'
11 THEN 1
12 ELSE 0
13 END) moved_to_out_of_stock,
14 SUM( CASE WHEN status = 'Out of Stock' AND prior_status = 'In Stock'
15 THEN 1
16 ELSE 0
17 END) moved_to_in_stock
18 FROM (SELECT item,
19 location,
20 status,
21 lag( status ) over (partition by item, location
22 order by dt) prior_status
23 FROM (SELECT item,
24 location,
25 (case when inventory <= 0
26 then 'Out of Stock'
27 else 'In Stock'
28 end) status,
29 dt
30 FROM your_table))
31* GROUP BY item, location
SQL> /
ITEM LOCATION MOVED_TO_OUT_OF_STOCK MOVED_TO_IN_STOCK
---------- ---------- --------------------- -----------------
1243 10 1 1