簡體   English   中英

如何編寫 redshift aws 查詢以搜索逗號分隔值中的值

[英]How to write redshift aws query to search for a value in comma delimited values

表格1

用戶身份 國家代碼
1 'IN,AU,AC'
2 'MX,IN'

表2

用戶身份 有效國家
1 '在'
1 '非盟'
2 'MX'
3 'YT'
4 '如'

如您所見,country_code 列中的某些條目是多個用逗號分隔的代碼。 我只想在 table1 中打印 user_id 及其相應的 country_code ,前提是它們有效。 要在這里檢查有效性,我需要使用具有 user_id 和 valid_country 的 table2。

所需的 output 是:

用戶身份 國家代碼
1 '在'
1 '非盟'
2 'MX'

查詢看起來像

select tb1.user_id, country_code from table1 tb1, table2 tb2 where tb1.user_id=tb2.user_id and <這里我需要檢查tb1.country_code中是否有tb2.country_code(代碼用逗號分隔)>

是否有任何簡單的解決方案可以在逗號分隔值中檢查 valid_country。

簡單的方法並不總是最好的。 這里可能會出現許多極端情況(例如所有國家/地區代碼都是 2 個字母)。 也就是說,LIKE 子句很簡單:

select tb1.user_id, valid_country as country_code
from table1 tb1, table2 tb2 
where tb1.user_id=tb2.user_id 
  and tb1.country_code like '%'||tb2.valid_country||'%'

或者,如果我們要把它放在現代 SQL 語法中:

select tb1.user_id, valid_country as country_code
from table1 tb1 join table2 tb2 
on tb1.user_id=tb2.user_id 
  and tb1.country_code like '%'||tb2.valid_country||'%'

嘗試這個:

a) 通過CROSS JOINtb1與一系列連續整數(我在公用表表達式中提供)垂直化,並應用SPLIT_PART() function 將逗號分隔的列表分解為單個元素。

b) INNER JOIN垂直化結果與有效的 user_id/國家代碼組合表在兩列的等值連接上。

WITH   
-- your table 1, don't use in end query ...                                                                                                                                                                                      
tb1(user_id,country_code) AS (
          SELECT 1,'IN,AU,AC'
UNION ALL SELECT 2,'MX,IN'
)
,
-- your table 2, don't use in end query ...                                                                                                                                                                                      
tb2(user_id,valid_country) AS (
          SELECT 1,'IN'
UNION ALL SELECT 1,'AU'
UNION ALL SELECT 2,'MX'
UNION ALL SELECT 3,'YT'
UNION ALL SELECT 4,'RU'
)
-- real query starts here, replace following comma with "WITH" ...
,
i(i) AS ( -- need a series of integers ...
          SELECT 1
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4
UNION ALL SELECT 5
)
,
vertical AS (
  SELECT
    tb1.user_id
  , i
  , SPLIT_PART(country_code,',',i) AS valid_country
  FROM tb1 CROSS JOIN i
  WHERE SPLIT_PART(country_code,',',i) <> ''
)
SELECT
  vertical.user_id
, vertical.valid_country
FROM vertical
JOIN tb2 USING(user_id,valid_country)
ORDER BY vertical.user_id,vertical.i
;
-- out  user_id | valid_country 
-- out ---------+---------------
-- out        1 | IN
-- out        1 | AU
-- out        2 | MX

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM