Actually I really don't know the appropriate title that will makes it unique as a question. Believe me, I tried my best to search about inner join
, union
, distinct
just to make my query done.
I only have one table and it looks like this:
ID | ITEM | MESSAGE_INFO | PARENT_ID | IS_CLOSED | IS_APPROVAL
1 | A123 | test 1 | null | 1 | 1
2 | A123 | reply to.. | 1 | null | null
3 | A123 |another reply.| 1 | null | null
4 | B456 | test 2 | null | null | 1
5 | A123 | new test 1 | 1 | null | 1
6 | C789 | test 3 | null | 2 | 1
7 | C789 | reply to 3 | 6 | null | null
Note:
- Message from the original author will have
1
inIS_APPROVAL
column and thePARENT_ID
isnull
it means that this is the original message that was sent.IS_CLOSED
will contain1
if the conversation is still open,2
if the original author can no longer reply to it,null
it means the receiver didn't open the message yet. PARENT_ID
will contain theID
where the message is replying to.- Message reply to the original author will have
null
inIS_CLOSED
column
Now what I want to do is I want to get the most recent message from the original author for each item. So the expected result is like this:
ID | ITEM | MESSAGE_INFO | PARENT_ID | IS_CLOSED | IS_APPROVAL
5 | A123 | new test 1 | 1 | null | 1
4 | B456 | test 2 | null | null | 1
I tried this query:
SELECT *
FROM TABLE
WHERE IS_APPROVAL = 1
AND (
IS_CLOSED IS NULL
OR IS_CLOSED < 2
)
GROUP BY ITEM
ORDER BY ID DESC;
But the result I'm getting is this:
ID | ITEM | MESSAGE_INFO | PARENT_ID | IS_CLOSED | IS_APPROVAL
1 | A123 | test 1 | null | 1 | 1
4 | B456 | test 2 | null | null | 1