I have a table with the history of the "Code" value changes. Every month this table gets a new record with the new value of the "Code" for the specified month.
+----------+------------+------------+------+
| Employee | FromDate | ToDate | Code |
+----------+------------+------------+------+
| Employee | 01/07/2016 | 31/07/2016 | 4 |
| Employee | 01/06/2016 | 30/06/2016 | 2 |
| Employee | 01/05/2016 | 31/05/2016 | 2 |
| Employee | 01/04/2016 | 30/04/2016 | 3 |
| Employee | 01/03/2016 | 31/03/2016 | 3 |
| Employee | 01/02/2016 | 29/02/2016 | 4 |
| Employee | 01/01/2016 | 31/01/2016 | 4 |
+----------+------------+------------+------+
I need to group by this data to get a new record every time "Code" changes and take the min value for the "From date" and the max value for the "To date". Data must be ordered descending by "FromDate". With my query I got this result:
+----------+------------+------------+------+
| Employee | FromDate | ToDate | Code |
+----------+------------+------------+------+
| Employee | 01/05/2016 | 30/06/2016 | 2 |
| Employee | 01/03/2016 | 30/04/2016 | 3 |
| Employee | 01/01/2016 | 31/07/2016 | 4 |
+----------+------------+------------+------+
It works fine but if the same "Code" has more the one date range (see the 4 code in the first table) I got a single row per code. I would like get this result with the 4 code in 2 records because its period is not continuos but it's broke by others codes (3 and 2):
+----------+------------+------------+------+
| Employee | FromDate | ToDate | Code |
+----------+------------+------------+------+
| Employee | 01/07/2016 | 31/07/2016 | 4 |
| Employee | 01/05/2016 | 30/06/2016 | 2 |
| Employee | 01/03/2016 | 30/04/2016 | 3 |
| Employee | 01/01/2016 | 29/02/2016 | 4 |
+----------+------------+------------+------+
I use this query:
SELECT
d."Employee",
MIN (d."FromDate") AS "FromDate",
MAX (d."ToDate") AS "ToDate",
d."Code"
FROM
(
SELECT
"Employees"."FromDate",
"Employees"."ToDate",
"Employees"."Code",
"Employees"."Employee"
FROM
schema_estelspa."Employees"
ORDER BY
"Employees"."FromDate" DESC
) d
GROUP BY
d."Code",
d."Employee"
ORDER BY
(MIN(d."FromDate")) DESC
Is there any trick to get the result I desired?
Date format is: dd/MM/yyyy