0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQLで共通の開始文字列を抽出する

Posted at

やりたいこと

このようなレコードから「東京都港区芝公園4丁目」を抽出したい。

  • 東京都港区芝公園4丁目2−8 東京タワー
  • 東京都港区芝公園4丁目7−35 増上寺

なかなか標準で用意されているものだけでは解決できなくて、結果、集約関数を実装して解決した。

$ psql --version
psql (PostgreSQL) 14.13 (Homebrew)
create or replace function intersect_prefix(state text, next_value text)
returns text language plpgsql as $$
declare
  subject text;
begin
  if state is null then
    return next_value;
  else
    subject := next_value;
    loop
  	  if length(subject) is null then
        return null;
  	  end if;

  	  if starts_with(state, subject) then
        return subject;
      end if;

      subject := substring(subject, 1, length(subject) - 1);
    end loop;
  end if;
end;
$$;

create or replace aggregate intersect_prefix(text)
( sfunc = intersect_prefix,
  stype = text);

検証

SELECT
  intersect_prefix(column1)
FROM (
  VALUES ('東京都港区芝公園4丁目2−8 東京タワー'), 
         ('東京都港区芝公園4丁目7−35 増上寺'));

-- 結果
'東京都港区芝公園4丁目'
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?