我有一个存储股票市场数据的数据库。
有一个包含3列的表格: stockId , date 和 volume
每个交易日都会在表格中插入新数据。
如何获得“过去10个交易日内每只股票的平均交易量”这样的结果?
答案 0 :(得分:1)
SELECT SUM(volume)/10 FROM table_name
Where date Between Cast('7/18/13 12:01:01' As DateTime) And Cast('7/08/13 12:01:01' as DateTime)
答案 1 :(得分:1)
SELECT AVG(volume) FROM mytable WHERE date >= (CURDATE() - INTERVAL 10 DAY)
修改强>
最近10天的小组及其平均值。
SELECT AVG(volume) FROM mytable GROUP BY date ORDER BY date DESC LIMIT 10
答案 2 :(得分:1)
http://sqlfiddle.com/#!6/c8dbb/4
CREATE TABLE Stocks
([StockId] int, [Date] DateTime, [Volume] int)
;
INSERT INTO Stocks
([StockId], [Date], [Volume])
VALUES
(1, GetDate(), 1000),
(1, GetDate()+1, 2000),
(1, GetDate()+2, 4000),
(2, GetDate(), 1000),
(2, GetDate()+1, 1000),
(2, GetDate()+2, 500)
;
Select StockId, AVG(Volume) [AverageVolume]
FROM Stocks
WHERE [Date] >= DATEADD(dd, 0, DATEDIFF(dd, 0, GetDate())) - 10
Group by StockId
Order by StockId
答案 3 :(得分:1)
我基于Dodecapus的答案,并根据你给出的其他答案的评论。我只是在回答中包含查询,但请查看sqlfiddle以获取数据的工作示例。
http://sqlfiddle.com/#!6/91599/2
SELECT
StockId
,AVG(Volume) [AverageVolume]
FROM Stocks
WHERE [Date] IN
(
SELECT DISTINCT TOP 10 [Date] FROM Stocks ORDER BY [Date] DESC
)
GROUP BY StockId
ORDER BY StockId
仅当每个交易日有至少一只股票的成交量时才会生效。
答案 4 :(得分:0)
有趣的小写查询。这是:
SELECT AVG(x.Volume) FROM (SELECT Volume FROM StockTable WHERE Date BETWEEN
DATE_ADD(NOW(), INTERVAL -10 DAY) AND NOW())x
这是我用来构建一个样本表来处理SQLFiddle
:
CREATE TABLE StockTable (ID INT PRIMARY KEY AUTO_INCREMENT NOT NULL, Date DATETIME, Volume INT);
INSERT INTO StockTable (Date, Volume) VALUES (DATE_ADD(NOW(), INTERVAL 12 DAY), 1000), (DATE_ADD(NOW(), INTERVAL 1 DAY), 5000),
(DATE_ADD(NOW(), INTERVAL 0 DAY), 3000), (DATE_ADD(NOW(), INTERVAL -11 DAY), 6000), (DATE_ADD(NOW(), INTERVAL -5 DAY), 4000), (DATE_ADD(NOW(), INTERVAL 7 DAY), 9000);
以下是运行中查询的SQLFiddle的链接。 德尔>
查询背后的想法:我创建了一个派生表 x
,其中只包含过去10天内的卷。然后我计算该表中包含的卷的平均值。瞧!
修改强>
在阅读完其他答案和评论后,我明确地意识到了你在寻找什么。您希望在过去10天内获得股票市场中每只股票的平均。
我构建了样本表:
CREATE TABLE StockTable (StockId INT NOT NULL, Date DATETIME, Volume INT);
INSERT INTO StockTable (StockId, Date, Volume) VALUES (1, DATE_ADD(NOW(), INTERVAL 6
DAY), 1000), (2, DATE_ADD(NOW(), INTERVAL 1 DAY), 5000),
(2, DATE_ADD(NOW(), INTERVAL 0 DAY), 3000), (3, DATE_ADD(NOW(), INTERVAL -8 DAY),
6000), (1, DATE_ADD(NOW(), INTERVAL -5 DAY), 4000),
(2, DATE_ADD(NOW(), INTERVAL 7 DAY), 9000);
获得结果的查询是:
SELECT StockId, AVG(Volume) FROM StockTable WHERE Date BETWEEN DATE_ADD(NOW(),
INTERVAL -10 DAY) AND NOW() GROUP BY StockId
Here是指向运行中查询的SQLFiddle的链接。