[英]Checking multiple conditions in CASE expression SQL
I am trying to parse a free form text with a case expression and I am not able to get the results I am expecting.我正在尝试使用 case 表达式解析自由格式文本,但无法获得预期的结果。 Can you please suggest if I can achieve this in SQL?你能否建议我是否可以在 SQL 中实现这一目标?
Here I have shown some sample data in the SQL Fiddle link below, but the city_lookup table has 100s of rows because there are multiple cities in a state. The case statement was just an attempt to put them in appropriate buckets.在这里,我在下面的 SQL Fiddle 链接中显示了一些示例数据,但是 city_lookup 表有 100 行,因为 state 中有多个城市。case 语句只是试图将它们放入适当的桶中。 The free form text can contain multiple keywords which can contain cities from the lookup table(city_lookup) and for every such occurrence, we need to record the visited state of the user.自由格式文本可以包含多个关键字,这些关键字可以包含查找表 (city_lookup) 中的城市,对于每一个这样的出现,我们需要记录用户访问过的 state。 For example if the freeform text contains two cities, I should be able to write the output as two different rows with each city visited, for the same user.例如,如果自由格式文本包含两个城市,我应该能够将 output 写成两个不同的行,每个城市都访问过,对于同一个用户。
SQL Fiddle Link - http://sqlfiddle.com/#!7/61ef9 SQL 小提琴链接 - http://sqlfiddle.com/#!7/61ef9
DDL 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');
Query询问
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;
Input & Output输入 & 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
You need to JOIN
the city_lookup
table to the log_cities
table to get all the cities visited by a user:您需要将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: Output:
user_id state
123 california
123 texas
234 arizona
456 texas
567 arizona
567 texas
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.