【问题标题】:Get truncked data from a table - postgresSQL从表中获取截断的数据 - postgresQL
【发布时间】:2023-02-01 23:34:27
【问题描述】:

我想获取上个月的截断数据。我的时间是 unix 时间戳,我需要为每个特定日期获取过去 30 天的数据。 数据的形式如下:

{
"id":"648637",
"exchange_name":"BYBIT",
"exchange_icon_url":"https://cryptowisdom.com.au/wp-content/uploads/2022/01/Bybit-colored-logo.png",
"trade_time":"1675262081986",
"price_in_quote_asset":23057.5,
"price_in_usd":1,
"trade_value":60180.075,
"base_asset_icon":"https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579",
"qty":2.61,
"quoteqty":60180.075,
"is_buyer_maker":true,
"pair":"BTCUSDT",
"base_asset_trade":"BTC",
"quote_asset_trade":"USDT"
}

我需要根据trade_time截断数据 如何编写查询?

【问题讨论】:

  • 你能举例说明你期望输出的样子吗?我对“每个特定日期过去 30 天的数据”的外观感到有点困惑。
  • 是的,我想获取每天的交易次数COUNT(*)。比如那天发生了多少笔交易。
  • 我不清楚您是想将数据转换为 JSON,还是想在特定条件下查询这些 JSON 值。

标签: postgresql


【解决方案1】:

秘诀是 date_trunc 函数,它接受 timestamp with time zone 并将其截断为特定精度(小时、天、周等)。然后,您可以根据此值进行分组。

在您的情况下,我们需要首先将这些 un​​ix 时间戳转换为 timestamp with time zone,我们可以使用 to_timestamp 来完成,但这仍然是一个相当简单的查询。

SELECT
    date_trunc('day', to_timestamp(trade_time)),
    COUNT(1)
FROM pings_raw
GROUP BY date_trunc('day', to_timestamp(trade_time))

另一种方法是将所有内容都保留为数字,这可能会稍微快一些,但我发现它的可读性较差

SELECT
    (trade_time/(60*60*24))::int * (60*60*24),
    COUNT(1)
FROM pings_raw
GROUP BY (trade_time/(60*60*24))::int

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    相关资源
    最近更新 更多