2
1

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】DISTINCTで重複行をまとめる方法

Posted at

#書き方


SELECT DISTINCT 列名 FROM テーブル名;

#サンプルデータの作成

CREATE TABLE sample_players (
    no int NOT NULL,            -- 背番号
    last_name varchar(100),     -- 名
    first_name varchar(100),    -- 姓
    PRIMARY KEY (no)            -- 主キー
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
 
-- テストデータ
INSERT INTO sample_players VALUES('1', '山田','太郎');
INSERT INTO sample_players VALUES('2', '山田','太郎');
INSERT INTO sample_players VALUES('3', '山田','太郎');
INSERT INTO sample_players VALUES('4', '山田','Q太郎');

#DISTINCTを使わない場合

mysql> SELECT last_name from sample_players;

+-----------+
| last_name |
+-----------+
| 山田       |
| 山田       |
| 山田       |
| 山田       |
+-----------+

#DISTINCTを使う場合



mysql> SELECT DISTINCT last_name from sample_players;
+-----------+
| last_name |
+-----------+
| 山田       |
+-----------+

#複数行でDISTINCTを使う場合



mysql> SELECT DISTINCT last_name, first_name from sample_players;
+-----------+------------+
| last_name | first_name |
+-----------+------------+
| 山田       | 太郎       |
| 山田       | Q太郎      |
+-----------+------------+

#参照
【SQL入門】DISTINCTで重複行をまとめる方法をわかりやすく解説

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?