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 5 years have passed since last update.

[SQL Server] 重複レコードの抽出

Posted at

やりたいこと

テーブルの重複レコードを抽出する
忘れがちなのでメモ

サンプル

同一のcodeを持つレコードを抽出する
抽出するカラムは全カラム

test

--テーブル作成
CREATE TABLE test(
	 code int NOT NULL
	,accountname varchar(10) NULL
	,item varchar(10) NULL
)

--データをinsert
INSERT INTO test
VALUES(1, 'a', 'もも')
	,(2, 'b', 'メロン')
	,(1, 'a', 'スイカ')
	,(3, 'c', 'なし')

--重複を抽出
SELECT
	 a.code
	,a.accountname
	,a.item
FROM
	test AS a
WHERE
	EXISTS(
		SELECT
			*
		FROM
			test AS b
		WHERE
			a.code = b.code
		GROUP BY
			b.code
		HAVING COUNT(b.code) > 1
	)
ORDER BY
	a.code

結果

code accountname item
1 a もも
1 a スイカ

補足

複数条件で抽出したい時は、a.code = b.codeの部分に追加すればOK

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?