Alex
Alex

Reputation: 1073

Replace function with variable and use it in return value

I have sql query, where if the difference between 2 times is greater than 1440, then it will divide by 7, if not it will return the actual value. The problem is that I am repeating the code in the return value.

SELECT
'IF(TIMESTAMPDIFF(MINUTE, now(), end_at) > 1440, TIMESTAMPDIFF(MINUTE, now(), end_at)/ 7, TIMESTAMPDIFF(MINUTE, now(), end_at)) as minutesLeft'
FROM table

How can I replace the repeating code to look like this?

SELECT
'IF(TIMESTAMPDIFF(MINUTE, now(), end_at) > 1440, timestamp / 7, timestamp ) as minutesLeft'
FROM table

Upvotes: 0

Views: 200

Answers (1)

Giles
Giles

Reputation: 1667

You can try using in-statement assignments:

set @diff = null;
SELECT @diff := TIMESTAMPDIFF(MINUTE, now(), end_at),
IF( @diff > 1440, @diff / 7, @diff) as minutesLeft
FROM table

Wrap the select in a sub-query if you just want one column returned.

Upvotes: 1

Related Questions