Here I have query in which I am trying to avoid the negative symbol in the final output. But why do I get that negative symbol ?
I have try to use the replace() but it doesn’t work.
can you please help me with this ?
here is the query ..,
WITH Partitioned AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id, start_date ORDER BY customer_id, start_date) AS RowNumber
FROM data_bank.customer_nodes
)
SELECT
*,
CASE
WHEN RowNumber > 1 THEN 0
ELSE COALESCE(DATEDIFF( (SELECT MAX(start_date) FROM data_bank.customer_nodes WHERE start_date < a.start_date AND customer_id = a.customer_id), a.start_date), 0)
END AS Days_between
FROM Partitioned a
Here is the output I got from above query
3
Answers
Here, I’ve modified the CASE statement to calculate the difference as the maximum of 0 and the result of DATEDIFF. This way, even if the subquery’s result is greater than the current start_date, the negative value will be replaced by 0.
I think you are subtracting the larger date from the smaller date, so it’s showing negative number. Change the positions of
a.start_date
and(SELECT MAX(start_date)...)
in theDATEDIFF
function to ensure that you’re subtracting the smaller date from the larger date.When first argument of
DATEDIFF
is smaller than the second argument, then you get negative results. You can useABS()
function of mysql to convert negative values to unsigned values, as folllows:NOTE: I have only shared relevant portion of the updated query.