3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ORDER句でCASE文を使用する

Last updated at Posted at 2018-03-16

SQLのORDER句でCASE文を使用する

環境

Microsoft SQL Server

テーブル

テーブルに、優先順位を表すフィールドがある。優先順位は上位のものにだけ存在し、「1」から順に番号が振られている。
大半のレコードには優先順位がなく、それらの値は「」である。
このとき、優先順位があるものを先に表示し、優先順位がないものは名称順で表示したい。
table.PNG

クエリ

ORDER句の中でCASE文を使用する。優先順位があればその値とし、なければ999としてソートを行う。

SELECT m.MachineId, m.MachineCd, SpecialPriority, IsDelete
FROM Machines m
WHERE m.IsDelete = 'False'
ORDER BY 
	CASE WHEN m.SpecialPriority='' 
		THEN 999 
		ELSE CONVERT(INT, m.SpecialPriority) 
	END

検索結果

優先度がある場合とない場合に区別したCASE文が働き、結果が取得できた。
result.PNG

3
5
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?