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?

More than 3 years have passed since last update.

3列間の昇順ソートをMySQLで行う

Posted at

プログラマのためのSQL 第4版 18章を参考に、3列間のデータを昇順ソートする。

用途がよく分からないが、とりあえず出来たので残しておく。

テーブル作成

create table Foobar_18_3_xyz
(key_col integer not null primary key,
x varchar(20) not null,
y varchar(20) not null,
z varchar(20) not null
);

データ挿入

insert into
  foobar_18_3_xyz
values
  (1, 'A', 'B', 'C')
  ,(2, 'E', 'D', 'C')
  ,(3, 'D', 'E', 'C')
;

更新

update
  foobar_18_3_xyz f1,
  foobar_18_3_xyz f2,
  foobar_18_3_xyz f3
set
  f1.x  = case
          when f1.x between f1.y and f1.z then f1.y
          when f1.z between f1.y and f1.x then f1.y
          when f1.y between f1.z and f1.x then f1.z
          when f1.x between f1.z and f1.y then f1.z
          else f1.x end,
  f2.y = case
          when f2.x between f2.y and f2.z then f2.x
          when f2.x between f2.z and f2.y then f2.x
          when f2.z between f2.x and f2.y then f2.z
          else f2.y end,
  f3.z = case
          when f3.x between f3.z and f3.y then f3.y
          when f3.z between f3.x and f3.y then f3.y
          when f3.y between f3.z and f3.x then f3.x
          when f3.z between f3.y and f3.x then f3.x
          else f3.z end
where
  f1.x > f1.z or f1.x > f1.y
;

確認

select * from foobar_18_3_xyz;

結果

key_col|x|y|z|
-------|-|-|-|
      1|A|B|C|
      2|C|D|E|
      3|C|D|E|

テーブルに別名を付けるのがポイント。
SQL Serverだと別名を付けなくても可能らしいが、検証はしていない。

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?