我在Stackoverflow上看到了一些与比较行有关的问题,但没有一个像这个问题。我有一个表格,其列类似于:
- Month (Date (01-Jan-2013)
- Country (Varchar2)
- SubCustomer (Varchar2)
- FTE (Number) Represents a value that is manually entered by employees each month
我们可能会有一些这样的数据..
- 01-Jan-2013 USA Customer1 10
- 01-Feb-2013 USA Customer1 15
- 01-Mar-2013 USA Customer1 30
- 01-Jan-2013 BRA Customer2 100
- 01-Feb-2013 BRA Customer2 300
- 01-Mar-2013 BRA Customer2 50
我的目标是比较输入的FTE并在单独的列中提供警报,例如“高警报”或“低警报”或“确定”,如果输入的FTE是前一个月的+/- 2倍每个月+国家+ SubCustomer。我一直在玩不同的Case语句,但似乎无法让比较在每个月都有效。
使用上述数据,客户1将在2月至3月期间生成“高度警报”警报,客户2将生成1月至2月的高警报以及2月至3月的低警报。
答案 0 :(得分:1)
听起来你应该使用LAG / LEAD。
SELECT Month, Country, SubCustomer, FTE
, LAG(FTE, 1, 0) OVER (PARTITION BY Country, SubCustomer ORDER BY Month) as PrevFTE
FROM MyTable
您可以在这里找到一些很好的例子: http://www.oracle-base.com/articles/misc/lag-lead-analytic-functions.php
答案 1 :(得分:0)
试试这个:包含NULL或零的可能性
WITH TABLEDATA
AS (SELECT
TO_DATE ( '01-Jan-2013',
'DD-MON-YYYY' )
AS MONT,
'USA' AS COUNTRY,
'Customer1' AS SUBCUST,
0 AS FTE
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '01-Feb-2013',
'DD-MON-YYYY' )
AS MONT,
'USA' AS COUNTRY,
'Customer1' AS SUBCUST,
15 AS FTE
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '01-Mar-2013',
'DD-MON-YYYY' )
AS MONT,
'USA' AS COUNTRY,
'Customer1' AS SUBCUST,
30 AS FTE
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '01-Jan-2013',
'DD-MON-YYYY' )
AS MONT,
'BRA' AS COUNTRY,
'Customer2' AS SUBCUST,
100 AS FTE
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '01-Feb-2013',
'DD-MON-YYYY' )
AS MONT,
'BRA' AS COUNTRY,
'Customer2' AS SUBCUST,
300 AS FTE
FROM
DUAL
UNION ALL
SELECT
TO_DATE ( '01-Mar-2013',
'DD-MON-YYYY' )
AS MONT,
'BRA' AS COUNTRY,
'Customer2' AS SUBCUST,
50 AS FTE
FROM
DUAL)
SELECT
MONT,
COUNTRY,
SUBCUST,
FTE,
ROUND ( ( FTE
- PREVIOUS_FTE )
/ NULLIF ( PREVIOUS_FTE,
0 ),
2 )
* 100
CHANGE_IN_PERCENT,
CASE
WHEN ROUND ( ( FTE
- PREVIOUS_FTE )
/ NULLIF ( PREVIOUS_FTE,
0 ),
2 )
* 100 >= 200
THEN
'High Alert'
WHEN ROUND ( ( FTE
- PREVIOUS_FTE )
/ NULLIF ( PREVIOUS_FTE,
0 ),
2 )
* 100 <= 200
THEN
'Low Alert'
ELSE
'OK'
END
AS ALERTS
FROM
(SELECT
MONT,
COUNTRY,
SUBCUST,
FTE,
LAG ( FTE,
1 )
OVER (PARTITION BY COUNTRY, SUBCUST ORDER BY MONT)
PREVIOUS_FTE
FROM
TABLEDATA);
<强>结果:强>
MONT COUNTRY SUBCUST FTE CHANGE_IN_PERCENT ALERTS
1/1/2013 BRA Customer2 100 OK
2/1/2013 BRA Customer2 300 200 High Alert
3/1/2013 BRA Customer2 50 -83 Low Alert
1/1/2013 USA Customer1 0 OK
2/1/2013 USA Customer1 15 OK
3/1/2013 USA Customer1 30 100 Low Alert