I have a table like this:
STOCK_ID TRADE_TIME PRICE VOLUME 123 1 5 100 123 2 6 150 456 1 7 200 456 2 8 250
For each stock I want to get the latest price (where the latest is only max trade_time) and the aggregated volume, so in the above table I want to see:
123 6 250 456 8 450
I just found that the current request is not working (always), i.e. There is no guarantee that the selected price is always the latest:
select stock_id, price, sum(volume) group by stock_id
Can I do without subqueries? Thank!
Since you did not specify the database you are using, here is some kind of generic SQL that will do what you want.
SELECT b.stock_id, b.trade_time, b.price, a.sumVolume FROM (SELECT stock_id, max(trade_time) AS maxtime, sum(volume) as sumVolume FROM stocktable GROUP BY stock_id) a INNER JOIN stocktable b ON b.stock_id = a.stock_id and b.trade_time = a.maxtime
SQL Server 2005 CTE (Common Table Expression), , :
;WITH MaxStocks AS ( SELECT stock_id, price, tradetime, volume, ROW_NUMBER() OVER(PARTITION BY stock_ID ORDER BY TradeTime DESC) 'RowNo' FROM @stocks ) SELECT m.StockID, m.Price, (SELECT SUM(VOLUME) FROM maxStocks m2 WHERE m2.STock_ID = m.Stock_ID) AS 'TotalVolume' FROM maxStocks m WHERE rowno = 1
, , , , ....
select a.stock_id, b.price , sum(a.volume) from tablename a join (select stock_id, max(trade_time), price from tablename group by stock_id) b on a.stock_id = b.stock_id group by stock_id
@Stock (STOCK_ID int, TRADE_TIME int, PRICE int, VOLUME int)
@Stock (123,1,5,100), (123,2,6,150), (456,1,7,200), (456,2,8,250)
Stock_ID, , ( () @Stock B, B.Stock_ID = A.Stock_ID) @Stock A A.Trade_Time = ( max (Trade_Time) @Stock)
Source: https://habr.com/ru/post/1781733/More articles:How to get synchronization context for the shown second form - c #problem / firefox font rendering problem - firefoxAccessing items from a dictionary efficiently using pickle in Python - pythonC # Generics: How can I use them in general? - genericsC # calling backgroundWorker from a thread other than a user interface thread - multithreadingКак вызвать Ruby внутренние методы C в Ruby? - cA box that can open quickly with a lot of items - controlsDoes anyone know how they made this keyboard? - objective-cMapKit user location (Blue Dot & Circle) will not be displayed - iphoneTwo iPhones connected to a Mac can be deployed simultaneously? - iphoneAll Articles