简体   繁体   中英

Adding values to a column in SQL(Snowflake) from another table

I have two tables A,B

Table A:

uid  category  
 1     a     
 1     b     
 1     c     
 2     b     
 2     d     

Table B:

category
  d       
  e       

Table A contains user id and category
Table B contains top 2 most categories selected by the user

How can I add categories from table B to category column in table A but only the distinct value.

Final result

uid  category
 1      a     
 1      b     
 1      c     
 1      d
 1      e     
 2      b     
 2      d     
 2      e     

It is possible to generate missing rows by perfroming CROSS JOIN of distinct UID from tableA and categories from tableB:

WITH cte AS (
   SELECT A.UID, B.CATEGORY
   FROM (SELECT DISTINCT UID FROM tableA) AS A
   CROSS JOIN tableB AS B
)
SELECT A.UID, A.CATEGORY
FROM tableA AS A
UNION ALL 
SELECT C.UID, C.CATEGORY
FROM cte AS c
WHERE (c.UID, c.category) NOT IN (SELECT A.UID, A.CATEGORY
                                  FROM tableA AS A)
ORDER BY 1,2;

Sample input:

CREATE OR REPLACE TABLE tableA(uid INT, category TEXT)
AS
SELECT 1,'a' UNION ALL     
SELECT 1,'b' UNION ALL     
SELECT 1,'c' UNION ALL     
SELECT 2,'b' UNION ALL     
SELECT 2,'d';

CREATE OR REPLACE TABLE tableB(category TEXT)
AS
SELECT 'd' UNION ALL SELECT 'e';

Output:

在此处输入图像描述

Let union take care of duplicates

select uid, category
from t1
union 
select uid, category
from (select distinct uid from t1) t1 cross join t2
order by uid, category

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM