Question

I have to write a query to database, that has such table:

TABLE HISTORY:
ID | ITEM_ID | USER_ID | DATE

and

ITEM TABLE:
ID | NAME | OWNER_ID

History table contains a records of all operations with items by users. I have to write a query, that takes from HISTORY table all items, which are not in the hands of owner. So, it should take for each item last record and select from them only those, which holds in other than it's owner's hands.

I tried to write it using nested queries, but if I'm using such subquery:

SELECT ITEM_ID, MAX(DATE) 
FROM HISTORY
GROUP BY ITEM_ID

I can't take ID of this record. So, I can't loop over the nested queries result's, because I don't know an ID of their ID's.

Could you help me?

P.S. And could you advise me to the future, how to take from queries with group by clause the columns, which not in group by statement?

Was it helpful?

Solution

My understanding of the question is that you want all items whose most recent history entry was made by a non-owner user. Please correct me if I'm wrong.

select h.item_id
from item i
    inner join history h
        on h.item_id = i.id and i.owner_id != h.user_id
    inner join (select item_id, max(id), max(date) as date
                from history
                group by item_id) mh
        on mh.item_id = h.item_id and h.date = mh.date

The above query assumes a datetime with some guarantee of uniqueness in the date column. If not, you might be able to use history.id if it is a perfectly auto-incrementing identity column and you promise never to let anyone mess with (ok, maybe not that strict, but you get my point).

In this case:

select h.item_id
from item i
    inner join history h
        on h.item_id = i.id and i.owner_id != h.user_id
    inner join (select item_id, max(id) as id
                from history
                group by item_id) mh
        on mh.id = h.id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top