我有一张类似的表:
STOCK_ID TRADE_TIME PRICE VOLUME
123 1 5 100
123 2 6 150
456 1 7 200
456 2 8 250
对于每个股票我想获得最新价格(最新只是最大交易时间)和汇总交易量,所以对于上表我想看到:
123 6 250
456 8 450
我刚刚发现当前查询没有(始终)有效,即无法保证所选价格始终是最新的:
select stock_id, price, sum(volume) group by stock_id
这可以不用子查询吗?谢谢!
答案 0 :(得分:4)
因为你没有指定你正在使用的数据库这里有一些通用的SQL可以做你想要的。
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
答案 1 :(得分:3)
在SQL Server 2005及更高版本中,您可以使用CTE(公用表表达式)来获取您要查找的内容:
;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
既然你想要每笔股票的最后交易以及所有交易的交易量,我不知道你如何在没有子查询的情况下完全做到这一点,不过......
答案 2 :(得分:0)
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
答案 3 :(得分:0)
声明@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 =(从@Stock中选择max(Trade_Time))