致力于 postgres SQL。
我有一个表,其中有一列包含以下格式的值:
Set1/Set2/Set3/...
Seti 可以是每个 i 的一组值。它们由“/”分隔。
我想显示 set1/set2 形式的不同条目,也就是说 - 我想修剪或截断这些条目中的其余字符串。 也就是说,我想要所有不同的选项:
第一组/第二组
正则表达式会很好用:我想要模式的子字符串:.*/.*/
不显示其余部分。
我得到了:
select distinct column_name from table_name
但我不知道如何自己进行修剪。
尝试查看 w3schools 和其他网站以及在 google 中搜索 SQL trim/SQL truncate,但没有找到我要找的东西。
提前致谢。
最佳答案
mu is too short 如果正斜杠之间的字符串长度始终一致,则答案很好。否则,您将需要使用带有子字符串函数的正则表达式。
例如:
=> select substring('Set1/Set2/Set3/' from '^[^/]+/[^/]+');
substring
-----------
Set1/Set2
(1 row)
=> select substring('Set123/Set24/Set3/' from '^[^/]+/[^/]+');
substring
--------------
Set123/Set24
(1 row)
因此您对表的查询将变为:
select distinct substring(column_name from '^[^/]+/[^/]+') from table_name;
相关文档是http://www.postgresql.org/docs/8.4/static/functions-string.html 和 http://www.postgresql.org/docs/8.4/static/functions-matching.html .
关于string - 快速 SQL 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7412460/