我有下表:
id purch_d7 purch_d30
1 10 25
2 5 15
我想将其转置/旋转为这种格式
id purchase_count purch_window
1 10 purch_d7
1 25 purch_d30
2 5 purch_d7
2 15 purch_d30
我将如何在Vertica中进行此操作?另外,如果想将输出旋转/转置回原始视图,我该怎么做?
答案 0 :(得分:1)
您可以尝试使用UNION ALL
SELECT id,purch_d7 as purchase_count,'purch_d7' as purch_window FROM T
UNION ALL
SELECT id,purch_d30,'purch_d30' FROM T
答案 1 :(得分:0)
我想让代码显示我想做的事情。我将垂直旋转命名列到值和“值名称”。因此,我在提供的其他表格中添加了值名称。
在这里:
WITH
-- don't add this first one to your query - it's just your data ...
input(id,purch_d07,purch_d30) AS (
SELECT 1,10,25
UNION ALL SELECT 2, 5,15
)
,
-- real WITH clause starts here ...
-- add the possible purch types as an in-line table with labels
purch_window(purch_window) AS (
SELECT 'purch_d07'
UNION ALL SELECT 'purch_d30'
)
SELECT
id
, CASE purch_window
WHEN 'purch_d07' THEN purch_d07
WHEN 'purch_d30' THEN purch_d30
ELSE NULL
END AS purchase_count
, purch_window
FROM input CROSS JOIN purch_window
ORDER BY 1,3
;
然后向后旋转:...
WITH
input(id,purch_d07,purch_d30) AS (
SELECT 1,10,25
UNION ALL SELECT 2, 5,15
)
,
-- real WITH clause starts here ...
-- add the possible purch types as an in-line table with labels
purch_window(purch_window) AS (
SELECT 'purch_d07'
UNION ALL SELECT 'purch_d30'
)
,
pivoted AS (
SELECT
id
, CASE purch_window
WHEN 'purch_d07' THEN purch_d07
WHEN 'purch_d30' THEN purch_d30
ELSE NULL
END AS purchase_count
, purch_window
FROM input CROSS JOIN purch_window
)
SELECT
id
, SUM(CASE purch_window WHEN 'purch_d07' THEN purchase_count END) AS purch_d07
, SUM(CASE purch_window WHEN 'purch_d30' THEN purchase_count END) AS purch_d30
FROM pivoted
GROUP BY 1
ORDER BY 1
;
您要做的就是将其复制粘贴到您的vsql客户端(或用于连接Vertica的任何客户端中……)