2

I'm searching for a specific SQL Query to automatically set "Priority" cell value if the value of the "Days Left" is :

  • 7 days or less = High
  • 14 days or less = Medium
  • 30 days or less = Low
  • 31 days or more = Very Low

this is my table looks like

Tasks    |  Due Date      |  Days Left | 
---------+----------------+------------+
AAAAA    |  20/12/2019    |      3     |
BBBBB    |  25/12/2019    |      8     |
CCCCC    |  01/01/2020    |     15     |
DDDDD    |  17/01/2020    |     31     |

result i want

Tasks    |  Due Date      |  Days Left |  Priority  | 
---------+----------------+------------+------------+
AAAAA    |  20/12/2019    |      3     |     High   |
BBBBB    |  25/12/2019    |      8     |    Medium  |
CCCCC    |  01/01/2020    |     15     |     Low    |
DDDDD    |  17/01/2020    |     31     |   Very Low |

current mysql query

SELECT
tasks,
due_date,
DATEDIFF(due_date, CURDATE()) AS days_left,
____________________________________ AS priority
1
  • You need to do it with case when ... then w3schools Commented Dec 17, 2019 at 2:21

1 Answer 1

3

Use a CASE expression:

SELECT
    tasks,
    due_date,
    DATEDIFF(due_date, CURDATE()) AS days_left,
    CASE WHEN DATEDIFF(due_date, CURDATE()) <= 7  THEN 'High'
         WHEN DATEDIFF(due_date, CURDATE()) <= 14 THEN 'Medium'
         WHEN DATEDIFF(due_date, CURDATE()) <= 30 THEN 'Low'
         ELSE 'Very Low' END AS Priority
FROM yourTable;

Note that, as written, the above CASE expression does not need to check both sides of the inequality range. Rather, we capture higher priorities first, and then let the remaining cases flow to the next step in the CASE expression.

Sign up to request clarification or add additional context in comments.

2 Comments

i use datediff function to calculate days_left, but looks like it doesnt work with CASE expression, is there any way i can automatically calculate days_left and use CASE expression from that result?
@Gnometa Please check my edited answer. I misread your question initially (I think).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.