QuestDB 上的 UNPIVOT 表结果

问题描述 投票:0回答:1

我的查询结果如下所示。如您所见,我有一个

buy
列和一个
sell
列,但每一行上仅存在一个值或另一个值,另一列为 null。

"timestamp","symbol","buy","sell"
"2024-12-19T08:10:00.700999Z","ETH-USDT",,3678.25
"2024-12-19T08:10:00.736000Z","ETH-USDT",,3678.25
"2024-12-19T08:10:00.759000Z","ETH-USDT",,3678.0
"2024-12-19T08:10:00.772999Z","ETH-USDT",,3678.0
"2024-12-19T08:10:00.887000Z","ETH-USDT",3678.01,
"2024-12-19T08:10:00.950000Z","ETH-USDT",,3678.0

我想转换成一种格式,其中有一个

side
列和一个
price
列,侧面是
sell
buy
。这将是一个 unpivot,但在 QuestDB 上没有
unpivot
功能

"timestamp","symbol","side","price"
"2024-12-19T08:10:00.700999Z","ETH-USDT","sell",3678.25
"2024-12-19T08:10:00.736000Z","ETH-USDT","sell",3678.25
"2024-12-19T08:10:00.759000Z","ETH-USDT","sell",3678.0
"2024-12-19T08:10:00.772999Z","ETH-USDT","sell",3678.0
"2024-12-19T08:10:00.887000Z","ETH-USDT","buy",3678.01
"2024-12-19T08:10:00.950000Z","ETH-USDT","sell",3678.0

有什么有效的解决方法吗?

谢谢!

database time-series questdb
1个回答
0
投票

找到了一个简单的解决方案。我可以在两个查询之间执行 UNION ALL,然后丢弃空值

with pivoted AS (
 SELECT ... (my original query)
),
unpivoted AS (
  SELECT timestamp, symbol, 'buy' as side, buy as price FROM pivoted 
  UNION ALL 
  SELECT timestamp, symbol, 'sell' as side, sell as price FROM pivoted
)
SELECT * from unpivoted where price is not null order by timestamp;

image showing the expected results on a table

© www.soinside.com 2019 - 2024. All rights reserved.