Difference reports negative value

Using this query from this post

Difference Between 2 values in a query?

import "math"

First = from(bucket: "LB3000")
  |> range(start: today())
  |> filter(fn: (r) => r["deviceId"] == "Okuma-LB3000")
  |> filter(fn: (r) => r["dataItemId"] == "Lppartcount")
  |> toInt()
  |> first()

Last = from(bucket: "LB3000")
  |> range(start: today())
  |> filter(fn: (r) => r["deviceId"] == "Okuma-LB3000")
  |> filter(fn: (r) => r["dataItemId"] == "Lppartcount")
  |> toInt()
  |> last()

union(tables: [First, Last])
|> difference()

I get a negative number as a result. I am expecting a positive number. When I try the suggested

|> map(fn: (r) => ({r with _value: math.abs(x: r._value)}))

I get a runtime error

runtime error @19:4-19:60: map: type conflict: float != int

Any suggestions? @grant1 ?

@fastxl math.abs only accepts float values. You need to cast your value to a float and then back to an integer. Try the following:

|> map(fn: (r) => ({r with _value: int(v: math.abs(x: float(v: r._value)))}))
1 Like

Thanks @scott and very clear as always.

I was about to suggest trying to reverse the two lines in the First and Last queries, like this:

OLD:

  |> toInt()
  |> first()

NEW:

  |> first()
  |> toInt()

and then see if the original map function would work…
|> map(fn: (r) => ({r with _value: math.abs(x: r._value)}))

1 Like

@scott Thanks for the help. I’d like to expand this to get a daily count for the last 7 days or any time frame. For each function by day?

Forget it. I found your work here Flux: First, Last and the differnce per day that answered this question.