I am having following important columns in a table,
- customer_approval (boolean)
- created_at (datetime)
- updated_at (datetime)
There is a possibility that multiple records might be present for the day. One these records for a day might have customer_approval marked as TRUE.
How can we write a query to get result set as follows:
- select only one record per day even if multiple are present for that day
- First preference for selection of record must be given to record where customer_approval is true
- If records don't fit in the above criteria select the latest entry which was created or updated based on created_at or updated_at column for that day
- Select all the records based on a date range (From date - To Date) when they were created.
Also adding an example: Table Data
+--------+-------------------+------------+------------+
| row_id | customer_approval | created_at | updated_at |
+--------+-------------------+------------+------------+
| 1 | TRUE | 2017-12-01 | 2017-12-01 |
| 2 | FALSE | 2017-12-01 | 2017-12-01 |
| 3 | NIL | 2017-12-01 | 2017-12-01 |
| 4 | NIL | 2017-12-02 | 2017-12-02 |
| 5 | FALSE | 2017-12-03 | 2017-12-03 |
| 6 | NIL | 2017-12-03 | 2017-12-03 |
| 7 | NIL | 2017-12-04 | 2017-12-05 |
+--------+-------------------+------------+------------+
Expected ResultSet for Date Range 2017-12-01 & 2017-12-05 :
+--------+-------------------+------------+------------+
| row_id | customer_approval | created_at | updated_at |
+--------+-------------------+------------+------------+
| 1 | TRUE | 2017-12-01 | 2017-12-01 |
| 4 | NIL | 2017-12-02 | 2017-12-02 |
| 6 | NIL | 2017-12-03 | 2017-12-03 |
| 7 | NIL | 2017-12-04 | 2017-12-05 |
+--------+-------------------+------------+------------+
Thanks in advance.
P.S. Sorry about the poor table formatting.