简体   繁体   English

SQL数据聚合-将行转换为列-具有数十亿行的表

[英]SQL Data Aggregation - Convert rows into columns - Table with billions of rows

I have billions of rows in a table. 我的表中有数十亿行。 Just pasting a sample data. 只是粘贴样本数据。

ticker     trade_date          trade_time     Price      Volume
---------------------------------------------------------------
AKS         01242017             1025           9.995    75038
AKS         01242017             1030          10        86891
AKS         01242017             1031           9.97     52815
AKS         01242017             1036          10.03     83556
AKS         01242017             1037          10.05     92644

I want to sum the data by trade hour.Usual NYSE hours of 0930 to 1600 hrs. 我想按交易时间对数据求和。通常的纽约证券交易所时间为0930到1600小时。

I want to see the above data as follows 我想查看以下数据

ticker    tdate        1sthour       Avg Price        2nd hour   Avg price
---------------------------------------------------------------------------
AKS        01242017     161929          9.99            229015     10.02

The challenge is I have 42000 different tickers and most tickers may not have data in each hour. 挑战是我有42000个不同的行情自动收录器,大多数行情自动收录器可能没有每小时的数据。 In such cases I want 0 displayed for the hour in which there is no sale of stock. 在这种情况下,我要在没有售出股票的那一小时显示0。 Tried case with sum but result does not look good. 尝试过以总和为例,但结果看起来不好。

Volume is calculated as follows 1st hor 930 - 1030=75038+86891=169129 Avg price=(75038*9.995+86891*10)/(75038+86891) 体积计算方法如下:第一小时930-1030 = 75038 + 86891 = 169129平均价格=(75038 * 9.995 + 86891 * 10)/(75038 + 86891)

I think this will do what you want: 我认为这将满足您的要求:

select ticker, tdate,
       sum(case when tradetime >= '0930' and tradetime <= '1030' then volume else 0 end) as volume_1,
       avg(case when tradetime >= '0930' and tradetime <= '1030' then price end) as price_1,
       sum(case when tradetime > '1030' and tradetime <= '1130' then volume else 0 end) as volume_2,
       avg(case when tradetime >= '1030' and tradetime <= '1130' then price end) as price_2,
       . . . 
from t
group by ticker, tdate ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM