1
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 1 year has passed since last update.

SQLでJOINを使わず累計を出す方法(ウィンド関数)

1
Last updated at Posted at 2024-07-09

はじめに

売上などの累計を出すときにテーブルを自己結合してだしていましたが、ウィンドウ関数なるものを使えば簡単に出せると知ったので自分のメモとして残しておこうと思います。

コード

-- ウィンド関数を使った方法
SELECT
	  date
	, uriage as '今日の売上'
	, SUM(uriage) OVER(ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as '累計'
FROM 
	uriage_data
WHERE 
	date between '2023-01-01' and '2023-12-31'
ORDER BY 
	date;


-- JOINで実装する方法
SELECT
	  uriage_data_a.date,
	, MAX(uriage_data_a.uriage) as '今日の売上'
	, SUM(uriage_data_b.uriage)
FROM 
	uriage_data as uriage_data_a
LEFT JOIN 
	uriage_data as uriage_data_b
ON 
	uriage_data_a.date >= uriage_data_b.date
	AND uriage_data_b.date BETWEEN '2023-01-01' AND '2023-12-31'
WHERE 
	uriage_data_a.date between '2023-01-01' and '2023-12-31'
GROUP BY 
	uriage_data_a.date
ORDER BY 
	uriage_data_a.date;

ウィンド関数の方はdateでソートしたものに対して最初の行から現在の行までSUMして出力しています。
JOINの方は現在の日付以前のものをJOINしてSUMしています。

おわりに

ウィンド関数を使えばJOINするテーブルが増えたとしてもシンプルにかけるので良いと思いました。
今回は累計を出しましたが他にもn行前を取得などできたり色々な使い方ができそうです。
ただ、自分自身SQLの研修で複雑なクエリを1000行近く書いた経験が現在もいきていると思っているので、SQL勉強中の方はまずはJOINに慣れて頭の中でもある程度クエリが想像できるようになってから楽するために使う方がいいのかなと思いました。(本当に個人的な意見です...)

1
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
1
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?