Skip to content
Advertisement

Remove Duplicate Result on Query

could help me solve this duplication problem where it returns more than 1 result for the same record I want to bring only 1 result for each id, and only the last history of each record.

My Query:

Result of my query, but returns 3 or 5 identical ids with different histories I want to return only 1 id of each ticket, and only the last recorded history of each tick

wanted to return as below

I wanted to return as shown below, see that the field ch_description, and ch_history bring only the most recent records and only the last of each ticket listed, without duplication I wanted to bring this way could help me.

Advertisement

Answer

Two things jump out at me:

  1. You have listed “created at” as part of your “distinct on,” which is going to inherently give you multiple rows per ticket id (unless there happens to be only one)

  2. The distinct on should make the subquery on the ticket history unnecessary… and even if you chose to do it this way, you again are going on the “created at” column, which will give you multiple results. The ideal subquery, should you choose this approach, would have been to group by ticket_id and only ticket_id.

Slightly related:

  1. An alternative approach to the subquery would be an analytic function (windowing function), but I’ll save that for another day.

I think the query you want, which will give you one row per ticket_id, based on the history table’s created_at field would be something like this:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement