I have a table which contains stock transactions:
+------+----------------------+------------------+
| Item | Running Stock Total | Transaction Time |
+------+----------------------+------------------+
| foo | 4 | 2012-05-12 11:07 |
| bar | 3 | 2012-05-12 10:42 |
| bar | 3 | 2012-05-12 9:42 |
| bar | 2 | 2012-05-11 15:42 |
| foo | 3 | 2012-05-11 10:02 |
| bar | 3 | 2012-05-10 13:44 |
...etc...
+------+----------------------+------------------+
i.e. Any time something happens to stock, a row is created in this table- this may mean the stock level goes up (new stock ordered), down(stock sold) or remains unchanged (stock relocated).
I need to create an sql query that returns only the rows where the stock level has actually changed for a particular part, and it needs to show the changes in a “stock up” and “stock down” column.
i.e. 1 Item='bar'
+------+-----------+------------+----------------------+------------------+
| Item | Stock Up | Stock Down | Running Stock Total | Transaction Time |
+------+-----------+------------+----------------------+------------------+
| bar | 1 | 0 | 3 | 2012-05-12 9:42 |
| bar | 0 | 1 | 2 | 2012-05-11 15:42 |
| bar | 1 | 0 | 3 | 2012-05-10 13:44 |
+------+-----------+------------+----------------------+------------------+
e.g.2 Item='foo'
+------+-----------+------------+----------------------+------------------+
| Item | Stock Up | Stock Down | Running Stock Total | Transaction Time |
+------+-----------+------------+----------------------+------------------+
| foo | 1 | 0 | 4 | 2012-05-12 11:07 |
| foo | 2 | 0 | 3 | 2012-05-11 10:02 |
+------+-----------+------------+----------------------+------------------+
So something like…
SELECT
Item, {xyz} as 'Stock Up', {abc} as 'Stock Down', `Running Stock Total`, `Transaction Time`
FROM
`StockTransactions`
WHERE
`Item`='foo'
HAVING
('Stock Up'>0 or 'Stock Down'>0)
Can this be done?
See it on sqlfiddle. The outer query can obviously be omitted if you’re happy for the results to be ordered in ascending order of transaction time and with the extra
last_totalcolumn.