学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

データベース| HSQLDB | 06 | 整列(ソート)

<<前  [TOP]  次>>


SQLにはselectの出力を読み易く整列する機能があります。


まずは次の例を見て下さい。


【例1:テーブル「books2」の一部をで価格で整列】

select id, title, price from books2 where price between 0 and 1000 order by price;



「select id, title, price from books2 where price between 0 and 1000 order by price;」
「select id, title, price from books2 where price between 0 and 1000 order by price;」


【例2:テーブル「books」の一部を書名で整列】

select id, title, publisher from books order by title;



「select id, title, publisher from books order by title;」
「select id, title, publisher from books order by title;」


【例3:テーブル「books2」の一部をでIDと価格で整列】

select id, title, price from books2 where price between 0 and 1000 order by id, price;



「select id, title, price from books2 where price between 0 and 1000 order by id, price;」
「select id, title, price from books2 where price between 0 and 1000 order by id, price;」


整列の仕方には小さいものから大きいものへ順である昇順と、大きいものから小さいものへの順である降順との二種類があります。
order by 句に項目名を並べるだけだとデフォルト値がとられます。
通常は昇順がデフォルト値です。
もしも降順での整列をしたいのなら項目名の後ろに予約語「desc (desendingの略)」をつければよいです。
普段は使う必要はありませんが、もし整列の方向をはっきりと示したかったら予約語「asc (ascendingの略)」をつければ良いです。


【例4:テーブル「books2」の一部をで価格(降順)とID(昇順)で整列】

select id, title, price from books2 where price between 0 and 1000 order by price desc, id asc;



「select id, title, price from books2 where price between 0 and 1000 order by price desc, id asc;」
「select id, title, price from books2 where price between 0 and 1000 order by price desc, id asc;」


select文では項目名だけではなく項目名からなる式を置くことができました。
例えば「price * qty」の値で並べ換えるにはどうすればいいのでしょうか?
order by 句で指定しようにも項目名がありません。
そうした時にはselectの項目名リストの中で何番目の項目かを数えて、その数字で指定をすることができます。
この例では「price * qty」はselectリストで 5番目の項目なので次の様な指定ができます。


【例5:式で与えられたカラムを、数字で指定して整列】

select id, title, price, qty, price*qty from books2 order by 5 desc;



「select id, title, price, qty, price*qty from books2 order by 5 desc;」
「select id, title, price, qty, price*qty from books2 order by 5 desc;」


order by 句に項目名の代わりに見出し名を指定することができます。


【例6:見出し名を指定して、整列】

select id ID, title 書名, price 価格, qty 部数, price*qty 総売上 from books2 order by 総売上 desc;



「select id ID, title 書名, price 価格, qty 部数, price*qty 総売上 from books2 order by 総売上 desc;」
「select id ID, title 書名, price 価格, qty 部数, price*qty 総売上 from books2 order by 総売上 desc;」


↓↓クリックして頂けると励みになります。


<<前  [TOP]  次>>