MySQL 算術演算子・絶対値・四捨五入・文字列演算・日付と時刻の計算

算術演算子

SQLで使える主な算術演算子

演算子 意味
+ 足し算
引き算
* 掛け算
/ 割り算
% 余り

足し算

select 10 + 4, 15.8 + 7.03;

実行結果

引き算

select 10 - 4, 10.8 - 7.03;

実行結果

掛け算

select 10 * 4, 15.8 * 7.03;

実行結果

割り算

select 10 / 4, 10.8 / 7.03;

実行結果

余り

select 10 % 4, 15.8 % 7.03;

実行結果

絶対値の取得

数値の符号を考えない、ゼロからの距離の大きさを表す数値です。

100の絶対値 100
-100の絶対値 100
0の絶対値 0

select abs(-100);

出力結果は以下の通り100になります。

四捨五入

通常の消費税込みの金額

まず、通常のフォーマットで消費税込みの金額を出力してみます。

select id, name, price * 1.08 from テーブル名;

丸めの桁数を指定して四捨五入

構文:round(対象の数値,丸めの桁数)

参考例:

丸めの桁数に0を指定 小数点第1位で四捨五入 round(10.555,0) 11
丸めの桁数に1を指定 小数点第2位で四捨五入 round(10.555,1) 11.6
丸めの桁数に2を指定 小数点第3位で四捨五入 round(10.555,2) 11.56

実際に出力してみます。

丸めの桁数を0(小数点第1位で四捨五入)

select id, name, round(price * 1.08,0) from テーブル名;

実行結果は以下の通り小数点第1位で四捨五入されてます。

丸めの桁数を1(小数点第2位で四捨五入)

select id, name, round(price * 1.08,1) from テーブル名;

実行結果は以下の通り小数点第2位で四捨五入されてます。

丸めの桁数を2(小数点第3位で四捨五入)

select id, name, round(price * 1.08,1) from テーブル名;

実行結果は以下の通り小数点第3位で四捨五入されてます。

文字列の演算

ユーザー一覧を苗字+スペース+名前+さんのフォーマットで出力する

文字列連結には a || b  →文字列aと文字列bを連結

ただし、MySQL,SQL Server 2012以降ではconcat関数を使用

構文:concat(文字列,文字列2,文字列3・・・)

苗字:last_name  名前:first_name の列名の場合

select concat(last_name, ' ', first_name, 'さん') from テーブル名;

出力結果

日付と時刻の計算

演算子 意味
current_date 現在の日付
current_timestamp 現在の時刻
d + n n日後の日付
d – n n日前の日付
interval’ x hour’ x時間後の時刻
-interval’ x hour’ x時間前の時刻
extract 日付や時刻の特定の部分(年や月)までを取り出す

現在の日付

select current_date();

現在の時刻

select current_timestamp();

5日後の日付

select current_date() + 5;

5日前の日付

select current_date() - 5;

5時間後の時刻

select current_time() + interval 5 hour;

5時間前の時刻

select current_time() - interval 5 hour;

日付や時刻の特定の部分(年月)まで取り出す。

テーブルから注文日時(order_timeカラム)が2017年11月のレコードを取得する

select * from テーブル名 where extract(year_month from order_time) = 201711;

実行結果

テーブルから注文日時(order_timeカラム)が2017年のレコードを取得する

select * from テーブル名 where extract(year from order_time) = 2017;

実行結果

テーブルから注文日時(order_timeカラム)が10月のレコードを取得する

select * from テーブル名 where extract(month from order_time) = 10;

実行結果

スポンサーリンク
スポンサーリンク
SNSフォローボタン

フォローする

シェアする

  • このエントリーをはてなブックマークに追加
スポンサーリンク
スポンサーリンク