Reputation: 965
Sorry if this sounds silly. Right now, I only have a basic understanding of MySQL and relational databases. Basically I can only do some simple SELECTs ;)
As usual, I did my Google and StackOverflow research before posting this, but I couldn't find any suitable answer (the ones on SO were almost every time with "0" value).
I will try to make it as generic as possible so that it could be useful to somebody else.
Let's say I have two tables:
TBUY
qtyBuy : integer
dateBuy : datetime
TSELL
qtySell : integer
dateSell : datetime
I would like to be able to write a query so that I can have a resulting table of qtyBuy/qtySell SORTED by the "merge" of the two dates, e.g. if those two tables are the "history" of some items beign bought and sold, I would like to know the history of that item, sorted by date.
I know that it's fairly easy to make the two different SELECTs and then, in whatever programming language you are using, merging the result "by hand". But I was wondering if there was a better way using MySQL.
I was thinking something like
SELECT * FROM (SELECT * FROM tbuy UNION ALL SELECT * FROM tsell) ORDER BY whichDate?!
But I do not know how to specify "whichDate". Thank you.
Upvotes: 0
Views: 1695
Reputation: 106
instead of *
use the names of the columns then you can rename the dateBuy
and dateSell
columns to something lets say date
.
In the Order-part of the statement you can use the new name (dateMerged
) to order the resultset.
SELECT qtyBuy as qtyChange, dateBuy as dateMerged FROM tbuy
UNION ALL SELECT -1 * qtySell, dateSell FROM tsell
ORDER BY dateMerged
The resultset of UNION conains the columnnames of the first SELECT-statement, so you might use dateBuy too, but that is not a speaking name in the UNION...
Upvotes: 2
Reputation: 2235
Have you tried:
select "buy" as action, qtyBuy as item, dateBuy as actionDate
from TBUY
union all
select "sell" as action, qtySell as item, dateSell as actionDate
from TSELL
order by actionDate
?
Since I can't guess what is qtyBuy, I don't know if you instead should join the tables.
As soon as you want a date-line with no wholes, you need an extra table with the dates. SQL can only read and combine values, but not create them out of nothing.
Upvotes: 4