[英]Checking multiple conditions in CASE expression SQL
我正在嘗試使用 case 表達式解析自由格式文本,但無法獲得預期的結果。 你能否建議我是否可以在 SQL 中實現這一目標?
在這里,我在下面的 SQL Fiddle 鏈接中顯示了一些示例數據,但是 city_lookup 表有 100 行,因為 state 中有多個城市。case 語句只是試圖將它們放入適當的桶中。 自由格式文本可以包含多個關鍵字,這些關鍵字可以包含查找表 (city_lookup) 中的城市,對於每一個這樣的出現,我們需要記錄用戶訪問過的 state。 例如,如果自由格式文本包含兩個城市,我應該能夠將 output 寫成兩個不同的行,每個城市都訪問過,對於同一個用戶。
SQL 小提琴鏈接 - http://sqlfiddle.com/#!7/61ef9
DDL
create table city_lookup(city varchar(50), state varchar(50));
insert into city_lookup values('dallas', 'texas');
insert into city_lookup values('austin', 'texas');
insert into city_lookup values('phoenix', 'arizona');
insert into city_lookup values('tuscon', 'arizona');
insert into city_lookup values('fresno', 'california');
insert into city_lookup values('monterey', 'california');
create table log_cities
(user_id int, visited_log varchar(512));
INSERT INTO log_cities values(123, 'This user was in dallas also probably in monterey');
INSERT INTO log_cities values(234, 'Logged: visisted tuscon');
INSERT INTO log_cities values(456, 'In March she visited texas, austin');
INSERT INTO log_cities values(567, 'He was probably here in phoenix and austin');
詢問
select
user_id,
case
when visited_log like '%dallas%' then 'texas'
when visited_log like '%austin%' then 'texas'
when visited_log like '%phoenix%' then 'arizona'
when visited_log like '%tuscon%' then 'arizona'
when visited_log like '%fresno%' then 'california'
when visited_log like '%monterey%' then 'california'
else 'None' end visited_state
from
log_cities;
輸入 & Output
-- Actual output
123 texas
234 arizona
456 texas
567 arizona
-- Actual output expected
123 texas
123 california
234 arizona
456 texas
567 arizona
567 texas
您需要將JOIN
表log_cities
city_lookup
以獲取用戶訪問過的所有城市:
SELECT user_id,
state
FROM city_lookup c
JOIN log_cities l ON l.visited_log LIKE CONCAT('%', c.city, '%')
ORDER BY user_id, state
Output:
user_id state
123 california
123 texas
234 arizona
456 texas
567 arizona
567 texas
您可以使用string_split
來實現這一點。
select user_id, state
from log_cities lc
outer apply STRING_SPLIT(lc.visited_log, ' ') s
join city_lookup cl on cl.city = s.value
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.