instead of the OR operator, thus writing

问题描述 投票:0回答:1
instead of the long list of OR operators. Anyway this could turn out in a VERY LONG string, because I could be willing to enlarge the set of values to be looked for.

ALSO, this set of values will be used again in the (long) script, and it will be a problem if one day I'll have to rewrite them all coherently.So I tried putting these values in the return value of a function:and then using the following:

SELECT
event,
CASE
  WHEN
    event LIKE '%MURDER%' or
    event LIKE '%KILL%' or
    ... --and so on with many other possible values...
    event LIKE '%WAR%'
  THEN 'VIOLENCE'
  WHEN
    event LIKE '%MARRIAGE%' or
    event LIKE '%MARRIED%' or
    ... --and so on with many other possible values...
    event LIKE '%WIFE%'
  THEN 'RELATIONSHIP'
  ELSE NULL 
  END class_of_event
FROM TABLE history_facts

This seemed a good solution because I could just define or update the function once at the beginning of the script and then use it everywhere I needed it.The problem is that this method performs quite well in some cases and horribly in other cases.

CASE WHEN event LIKE '%MARRIAGE%|%MARRIED%|%WIFE%' THEN 'RELATIONSHIP' ELSE null END class_of_event

So, is there a way to: 1) write a synthetic version of 2) and store the strings I am looking for in some "global variable" that I can rewrite only once and re-use everywhere in the script?

CREATE OR REPLACE FUNCTION relationship_event()
  RETURNS text AS
$$SELECT text '%MARRIAGE%|%MARRIED%|%WIFE%'$$ LANGUAGE sql IMMUTABLE PARALLEL SAFE;

Thanks everybody, this is driving me crazy.I think I can do this easily with SAS or Python, but can't achieve it on POSTGRESQL

CASE WHEN event LIKE relationship_event() THEN 'RELATIONSHIP' ELSE null END class_of_event

event LIKE 'a' OR event LIKE 'b' OR event LIKE 'c' OR...This is a complex problem to explain, so I'll try to be as clear as I can. I have a CASE that returns a value according to a text filter by means of the LIKE operator. This set of values searched by ...

I know I can use the pipe
sql postgresql sql-like case-when sql-function
1个回答
3
投票
这是个复杂的问题,所以我尽量解释清楚。 我有一个CASE,通过LIKE操作符,根据文本过滤返回一个值。我需要生成1列(class_of_event)有N个可能的值,将一个给定的字符串分类在N个可能的类别中.这组由LIKE操作符搜索的值将在脚本中反复使用,并会偶尔更新。脚本大致是这样的。

我知道我可以使用管道

© www.soinside.com 2019 - 2024. All rights reserved.