首页 > 解决方案 > SQL 数据聚合 - 将行转换为列 - 包含数十亿行的表

问题描述

我在一张表中有数十亿行。只需粘贴示例数据。

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

我想按交易时间汇总数据。通常纽约证券交易所的交易时间为 0930 至 1600 小时。

我想看上面的数据如下

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

挑战是我有 42000 个不同的代码,大多数代码可能没有每小时的数据。在这种情况下,我希望在没有销售库存的小时内显示 0。尝试了 sum 但结果看起来不太好。

成交量计算如下 1st hor 930 - 1030=75038+86891=169129 平均价格=(75038*9.995+86891*10)/(75038+86891)

标签: sqloraclepivot

解决方案


我认为这会做你想要的:

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 ;

推荐阅读