我对使用presto的SQL非常陌生,我试图拆散如下所示的表:枢轴,使其看起来如下:无枢轴
我试过使用UNPIVOT函数,我尝试过与unnest交叉连接。我最终认为我已经用UNION找到了它,但是我可以安静地得到正确的查询。你能把我推向正确的方向吗?
这就是我在做的事情:
SELECT CASE_ID, Account, Amount
FROM
TEST_TABLE
CROSS JOIN UNNEST (
ARRAY['Factor_Cost','Unfactor_cost'],
ARRAY[Factor_Cost,Unfactor_cost]
) t2(account, amount)太感谢了,R
发布于 2021-12-15 10:41:00
你走在正确的轨道上。可以使用交叉连接+ case表达式来根据帐户价值计算金额:
SELECT t1.CASE_ID,
t2.Account,
case when t2.Account = 'Factor_Cost' then t1.factor_cost else t1.unfactor_cost end Amount
FROM
TEST_TABLE t1
CROSS JOIN (
values('Factor_Cost'),('Unfactor_cost')
) t2(account)交叉联接将通过帐户值和大小写表达式复制行,以从t1获取相应的列作为金额。
或相同使用交叉联接UNNEST,没有大小写表达式:
SELECT t1.CASE_ID,
t2.Account,
t2.Amount
FROM
TEST_TABLE t1
CROSS JOIN UNNEST(
ARRAY['Factor_Cost','Unfactor_cost'],
ARRAY[t1.factor_cost,t1.unfactor_cost]
) t2(account,amount)或使用UNION ALL (效率较低的方法)
SELECT CASE_ID, 'Factor_Cost' Account, factor_cost Amount from TEST_TABLE t1
union all
SELECT CASE_ID, 'Unfactor_cost' Account, unfactor_cost Amount from TEST_TABLE t1所有这些查询都可以产生不同排序的结果。只有使用额外的订单才能保证相同的订单。
https://stackoverflow.com/questions/70359858
复制相似问题