So I'm having a bit of a problem with a nested select I'm trying to do on a table of data.
I have a number of books across a number of libraries. Each book has an ID and each location a name. Every time a book is taken out or returned, a transaction is recorded on a transaction table.
The table looks a little like this:
+---------+--------+----------+------------+
| BOOK_ID | IN_OUT | LOCATION | DATE |
+---------+--------+----------+------------+
| B01 | O | RED | 2013-10-04 |
| B02 | O | BLUE | 2013-10-04 |
| B01 | I | RED | 2013-10-19 |
| B01 | O | RED | 2013-10-20 |
| B02 | I | RED | 2013-10-21 |
| B01 | I | BLUE | 2013-10-24 |
+---------+--------+----------+------------+
(Thanks, @Senseful!)
Right now, I can show all transactions and their in_time, out_time displayed in pairs:
SELECT i.BOOK_ID
,(SELECT MAX(o.DATE)
FROM TRANSACTIONS o
WHERE (o.IN_OUT = 'O')
AND o.BOOK_ID = i.BOOK_ID
AND o.DATE < i.DATE
) AS out_time
, i.DATE AS in_time
, LOCATION
FROM TRANSACTIONS i
WHERE i.IN_OUT = 'I'
ORDER BY i.DATE
;
Now, however, I'm wanting to only display transactions where books are being returned to a different location: so in the example above, I've tried selecting LOCATION as out_location with the intention of adding a WHERE clause to check if it is equal to in_location.
Fair enough:
,(SELECT MAX(o.DATE), LOCATION as out_location
FROM TRANSACTIONS o
No can do. "ORA-00913: too many values
".
Any ideas on what would be the most sensible way of limiting the output like this?