PIVOT 按时间戳

Posted

技术标签:

【中文标题】PIVOT 按时间戳【英文标题】:PIVOT by timestamp 【发布时间】:2022-01-23 19:12:15 【问题描述】:

我需要为此查询的结果转置时间(小时),因此您可以在 Excel 数据透视表中复制最多 24 小时。有没有一种简单有效的方法可以在查询中复制它?

查询:

SELECT
  trunc(complete_dstamp) "Date", 
  to_char(complete_dstamp, 'HH24') "Hour", 
  user_id "User", 
  sum(update_qty) "Qty" 
FROM
  inventory_transaction 
WHERE
  to_loc_id = 'CONTAINER' 
  and trunc(complete_dstamp) > (
    trunc(current_timestamp)-1
  ) 
GROUP BY
  trunc(complete_dstamp), 
  to_char(complete_dstamp, 'HH24'), 
  user_id 
ORDER BY
  1, 
  2

期望的输出:

当前输出:

【问题讨论】:

【参考方案1】:

使用条件聚合:

SELECT TO_CHAR(complete_dstamp, 'YYYY-MM-DD') AS "Date",
       user_id AS "User",
       SUM(CASE TO_CHAR(complete_dstamp, 'HH24') WHEN '00' THEN update_qty END) AS hour_0,
       SUM(CASE TO_CHAR(complete_dstamp, 'HH24') WHEN '01' THEN update_qty END) AS hour_1,
       SUM(CASE TO_CHAR(complete_dstamp, 'HH24') WHEN '02' THEN update_qty END) AS hour_2,
       SUM(CASE TO_CHAR(complete_dstamp, 'HH24') WHEN '03' THEN update_qty END) AS hour_3,
       SUM(CASE TO_CHAR(complete_dstamp, 'HH24') WHEN '04' THEN update_qty END) AS hour_4,
       -- ...
       SUM(CASE TO_CHAR(complete_dstamp, 'HH24') WHEN '23' THEN update_qty END) AS hour_23,
       sum(update_qty) AS grand_total
FROM   inventory_transaction
WHERE  to_loc_id = 'CONTAINER'
AND    complete_dstamp >= trunc(current_timestamp)
GROUP BY
       TO_CHAR(complete_dstamp, 'YYYY-MM-DD'),
       user_id
ORDER BY
       "Date",
       "User"

或者PIVOT

SELECT "Date",
       user_id AS "User",
       hour_0,
       hour_1,
       hour_2,
       hour_3,
       hour_4,
       -- ...
       hour_23,
       COALESCE(hour_0, 0)
       + COALESCE(hour_1, 0)
       + COALESCE(hour_2, 0)
       + COALESCE(hour_3, 0)
       + COALESCE(hour_4, 0)
       -- ...
       + COALESCE(hour_23, 0) AS grand_total
FROM   (
  SELECT TO_CHAR(complete_dstamp, 'YYYY-MM-DD') AS "Date",
         TO_CHAR(complete_dstamp, 'HH24') AS hour,
         user_id,
         update_qty
  FROM   inventory_transaction
  WHERE  to_loc_id = 'CONTAINER'
  AND    complete_dstamp >= trunc(current_timestamp)
)
PIVOT (
  SUM(update_qty) FOR hour IN (
     '00' AS hour_0,
     '01' AS hour_1,
     '02' AS hour_2,
     '03' AS hour_3,
     '04' AS hour_4,
    -- ...
    '23' AS hour_23
  )
)

db小提琴here

【讨论】:

完美,感谢 MTO

以上是关于PIVOT 按时间戳的主要内容,如果未能解决你的问题,请参考以下文章

当时间戳未被归类为索引时,如何按时间戳对数据帧进行切片?

按时间戳写入分区数据

Python Pandas:按日期分组,并按时间戳访问每个组

Pandas DataFrame 按时间戳分组

按最近的时间戳对数组中的对象数组进行排序,然后使用 jq 按每个数组的第一个对象的时间戳对外部数组进行排序

Hbase如何按时间戳排序