我有一个格式如下的查询输出:
年月 | 销售 | 交易 | 物品 | 运费 | 税 |
---|---|---|---|---|---|
2024-04 | 20 | 50 | 100 | 12 | 2 |
2024-03 | 10 | 25 | 50 | 6 | 1 |
这不是查看数据的好方法,因为数据比我上面放入的列更多。
我想做的是通过 SQL 转置数据,使数据看起来像这样:
2024-04 | 2024-03 | |
---|---|---|
销售 | 20 | 10 |
交易 | 50 | 25 |
物品 | 100 | 50 |
运费 | 12 | 6 |
税 | 2 | 1 |
使用这种格式,更多数量的指标将以呈现此信息的格式更具可读性。
我已经尝试遵循一些指南来使用 UNPIVOT 和 UNION ALL 函数,但没有成功,因为我看过的指南只是将一个单一列移动到一行,而不是更大的数量。
查询参考 - 初始输出:
select
YR_MO,
sum(order_volume) as Sales,
sum(transaction_count) as Transactions,
sum(items_shipped) as Items,
sum(freight_charge) as ShippingCost,
sum(tax_incurred) as Tax
from consolidated_data
group by 1
试试这个。首先将列“销售额、交易、项目、成本、税”转换为行。之后将行“2024-04,2024-03”转换为列。
查询:
select
type,
max(case when yr_mo='2024-04' then val end) as `2024-04`,
max(case when yr_mo='2024-03' then val end) as `2024-03`
from (
select case when rn=1 then 'Tax' when rn=2 then 'Shipping_Cost' when rn=3 then 'Items' when rn=4 then 'Transactions' when rn=5 then 'Sales' else '' end as type,
yr_mo, val
from (
select
yr_mo,
row_number() over(partition by yr_mo) as rn,
val
from sales_table
lateral view explode(array(sales,transactions,items,cost,tax)) org as val) calcultd ) calcultd2
group by type;