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.

SQLで条件付きソートを実施する(Postgres編)

Posted at

SQLで条件付きソートを実施する。

下記のようなDDLがあった場合、第1ソートキーが科目=数学,第2ソートキーが成績でソートしたい。ただ、国語や他の科目も表示したいため、Whereで絞りたくはない。

DDL
CREATE TABLE IF NOT EXISTS users(
   id serial PRIMARY KEY,
   username VARCHAR (256) UNIQUE NOT NULL
);

CREATE TABLE IF NOT EXISTS subject(
   id serial PRIMARY KEY,
   user_id int,
   name VARCHAR (256) NOT NULL,
   score int,
   date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

ALTER TABLE "subject" ADD FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE SET NULL ON UPDATE NO ACTION;
SQL
SELECT * from users as u INNER join subject as s on u.id = s.user_id order by name='数学' desc, score desc;

id	username	id	user_id	name	score	date
2	kkfactory	6	2	数学	89	2022-06-02 06:17:57.970721
1	koji	4	1	数学	67	2022-06-02 06:17:57.970721
1	koji	1	1	国語	86	2022-06-02 06:17:57.970721
2	kkfactory	2	2	国語	78	2022-06-02 06:17:57.970721
3	takashi	3	3	国語	56	2022-06-02 06:17:57.970721
1	koji	5	1	国語	44	2022-06-02 06:17:57.970721

実施するまでは悩んでるけど、やってみると意外とさっくり行ける!!SQL便利!!!

0
0
1

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?