If statement in

I am aggregating sql from a select query into a json array like this:

CONCAT('[',GROUP_CONCAT(JSON_OBJECT('value', measured_at, 'day', datediff(measurements.measured_at, athletes.tracking_started_at))), ']') as `values`

At times the json object returns a negative value from the datediff. What I’d like to do is not return a json object at all in that case.

eg. what I get now:

[{ "value": 23, "day": 12 }, { "value": 23, "day": -25 }, { "value": 23, "day": 40 }]

what I’d like to get:

[{ "value": 23, "day": 12 }, { "value": 23, "day": 40 }]

How can I do this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use a CASE expression inside GROUP_CONCAT():

GROUP_CONCAT(
  CASE 
    WHEN datediff(measurements.measured_at, athletes.tracking_started_at) >= 0 
      THEN JSON_OBJECT('value', measured_at, 'day', datediff(measurements.measured_at, athletes.tracking_started_at))
  END
)


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x