试试这个:包含 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