[英]How to put the result of two different columns with same data type within one column such that both rows from both tables are unique in target table
For example I have two columns:例如我有两列:
Column A: dog, cat, mouse
Column B: truck, jeep, lorry
I want a situation where:我想要一种情况:
Column C : dog, truck, cat, jeep, mouse, lorry
I am using Snowflake我正在使用雪花
Assuming that columns colA, colB are strings, the values should be first splitted to atomic values SPLIT_TO_TABLE and combined again LISTAGG:假设 colA、colB 列是字符串,则应首先将值拆分为原子值 SPLIT_TO_TABLE 并再次组合 LISTAGG:
SELECT ID, COLA, COLB, LISTAGG(COL, ', ') AS colC
FROM (
SELECT ID, COLA, COLB, TRIM(s1.VALUE::STRING) AS col
FROM tab
,TABLE(SPLIT_TO_TABLE(tab.colA, ',')) AS s1
UNION
SELECT ID, COLA, COLB, TRIM(s2.VALUE::STRING) AS col
FROM tab
,TABLE(SPLIT_TO_TABLE(tab.colB, ',')) AS s2
) AS sub
GROUP BY ID, COLA, COLB
ORDER BY ID;
For sample data:对于样本数据:
CREATE OR REPLACE TABLE tab
AS
SELECT 1 AS id, 'dog, cat, mouse' AS colA, 'truck, jeep, lorry' AS colB UNION
SELECT 2 AS id, 'sparrow' AS colA, 'sparrow, parrot' AS colB;
Output: Output:
Sidenote: For storing non-atomic values ARRAY is a better choice:旁注:对于存储非原子值 ARRAY 是更好的选择:
CREATE OR REPLACE TABLE tab
AS
SELECT 1 AS id, ['dog', 'cat', 'mouse'] AS colA, ['truck', 'jeep', 'lorry'] AS colB UNION
SELECT 2 AS id, ['sparrow'] AS colA, ['sparrow', 'parrot'] AS colB;
Then combining is a matter of using ARRAY_UNION_AGG :然后组合是使用ARRAY_UNION_AGG的问题:
SELECT ID, ARRAY_UNION_AGG(COL) AS COLC
FROM (
SELECT ID, COLA AS col FROM tab
UNION ALL
SELECT ID, COLB AS col FROM tab
) sub
GROUP BY ID
ORDER BY ID;
Output: Output:
Consider a UNION query:考虑一个 UNION 查询:
SELECT 1 AS GrpID, FieldA AS Data FROM tablename
UNION SELECT 2, FieldB FROM tablename;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.