Sample table (incident) have the following data,
+-----+-------------+------+----------+
| Ref | In_Date | Item | Customer |
+-----+-------------+------+----------+
| 1 | 5-Apr-2018 | DELL | ABC |
| 2 | 11-Apr-2018 | DELL | ABC |
| 3 | 13-Apr-2018 | DELL | ABC |
| 4 | 19-Apr-2018 | DELL | ABC |
| 5 | 25-Apr-2018 | DELL | ABC |
| 6 | 27-Apr-2018 | DELL | ABC |
| 7 | 29-Apr-2018 | DELL | ABC |
| 8 | 10-Apr-2018 | HP | XYZ |
| 9 | 12-Apr-2018 | HP | XYZ |
| 10 | 30-Apr-2018 | IBM | JKL |
+-----+-------------+------+----------+
As per below query,will get the similar incidents (By Item & Customer) of count > 1.
SELECT * FROM
(
SELECT Ref, In_Date, Item, Customer,
COUNT(*) OVER (PARTITION BY Customer, Item) AS cnt
FROM Incident
) t
WHERE cnt > 1
ORDER BY Item, Customer;
I want to set a Flag for each result row with the following condition,
- Flag "0" when the day difference with its nearest date with more than 3 days in similar incident group (eg: Ref 1 & 4 result table)
- Flag "2" for the last date in similar incident group if it have nearest 3 days(eg: Ref : 3,7 & 9)
- Flag "1" for 3 days difference with latest date (eg: ref: 2, 5 ,6 & 8)
Expected Result:
+-----+-------------+------+----------+------+
| Ref | In_Date | Item | Customer | Flag |
+-----+-------------+------+----------+------+
| 1 | 5-Apr-2018 | DELL | ABC | 0 |
| 2 | 11-Apr-2018 | DELL | ABC | 1 |
| 3 | 13-Apr-2018 | DELL | ABC | 2 |
| 4 | 19-Apr-2018 | DELL | ABC | 0 |
| 5 | 25-Apr-2018 | DELL | ABC | 1 |
| 6 | 27-Apr-2018 | DELL | ABC | 1 |
| 7 | 29-Apr-2018 | DELL | ABC | 2 |
| 8 | 10-Apr-2018 | HP | XYZ | 1 |
| 9 | 12-Apr-2018 | HP | XYZ | 2 |
+-----+-------------+------+----------+------+