sql - 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)
解决方案
我认为这会做你想要的:
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 ;
推荐阅读
- python - 勒让德多项式 Python
- python - 如何检查字符串是否包含Python列表中的特定字符?
- java - 如何在 Cucumber 特征文件中传递具有不同数量参数的多个示例
- node.js - CORB 阻止跨域响应(错误的 MIME 类型)
- typescript - 如何在 Ionic React 中将道具传递给选项卡
- c++ - 在编译时检测 std::tuple 中的类型包含
- angular - 刷新页面时 AuthGuard 不起作用
- python - 通过不同的功能携带结果数据帧
- python - 向 JSON 对象挂钩添加类型提示的正确方法
- python - 如何测试方法中的单个调用?