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 データの並び替え,文字列の連結

Last updated at Posted at 2021-03-26

こちらの記事では、私が学んだSQLについて記載しております。
自身の忘れないためのメモとしております。
間違っている部分もあるかもしれませんので、ご了承ください。

order byを使用して並び順を指定する!

asc・・・昇順  並び順の指定がなければ、ascになる
desc・・・降順

select * from テーブル名 order by カラム名 asc; ←ascを省略しても良い!

select * from テーブル名 order by カラム名 desc;

複数の並び替え条件を指定する場合!

order byは、カンマ区切りで複数の並び替え条件を指定できる!
下記は、テーブル名のカラム名を降順に指定し、登録されたidの順番昇順になります。

select * from テーブル名 order by カラム名 desc, カラム名 asc;


例 ユーザー名を降順にし、そこから登録された順番に表記する場合
テーブル名 users  
カラム名 name , id

select * from users order by name desc, id asc;
           ↑
zから始まる名前を並べ、且つ、登録の順番で表記する。
*注意 アルファベットでのnameであれば並び替えの指定はできるが、日本語の文字列ではできない!!!

四捨五入を行うには、roundを使用する!

記述方法 round(対象の数値,小数点の桁)

例
round(99.888,0) => 100
         ↑最初が0番目になります
round(99.888,1) => 99.9
          ↑小数点から2個目の位置
round(99.888,2) => 99.89
           ↑小数点から3個目の位置

実際の記述
select カラム名 * 1.1 from テーブル名; 

select round(カラム名 * 1.1 , 0) from テーブル名;

文字列を連結させたい場合 concatを使用!

記述方法 concat(文字列1,文字列2,文字列3,,,,,,)
スペースを入れたい場合は、(' ')
                      ↑シングルクォーテーションの中にスペースを入れる!!

select concat('田中',' ','太郎',' 様');  => 田中 太郎 様 と取得可能です
             ↑スペース  ↑スペース     ↑  ↑ スペースが開いた状態になる。

select concat(カラム名,カラム名) from テーブル名;

日付と時刻の演算子

現在の日付・・・・・・current_date
現在の時刻・・・・・・current_timestamp
a日後の日付・・・・・current_date() + interval a day
a日前の日付・・・・・current_date() - interval a day
x時間後の時刻・・・・current_time() + interval x hour
x時間前の時刻・・・・current_time() - interval x hour
extract・・・・・・・・日付や時刻の特定部分まで取り出す

・記述例
select current_date();  =>現在の日付
select current_timestamp(); =>現在の時刻
select current_date() + interval 5 day; 5日後
select current_date() - interval 5 day; 5日前
select current_time() + interval 12 hour; 12時間後
select current_time() - interval 12 hour; 12時間前
select * from テーブル名 where extract(year_month from カラム名) = 202103; 2020年3月全てのカラムデータ取得する 
select * from テーブル名 where extract(year from カラム名) = 2020; 2020年全てのカラムデータ取得する
select * from テーブル名 where extract(month from カラム名) = 1; 1月のカラムデータ全て取得する

補足

絶対値 absで取得する

数値の符号を考えず、ゼロからの距離の大きさを表す数値です。
・100の絶対値は100
・−100の絶対値は100
・0の絶対値は0

絶対値の記述
select abs(100);
select abs(-100);
select abs(0);
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?