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

SQLで累積を取得する方法

Last updated at Posted at 2023-10-13

こんにちは:smiley:

SQLで累積を取得する方法を紹介します。

商品ごとに毎月の売上高の累積を求めます。

image.png

コーディング例①

  SELECT
    商品
    , FORMAT(売上年月, 'yyyy年MM月') AS 売上年月
    , 売上高
    ,SUM(売上高) OVER (PARTITION BY 商品 ORDER BY 売上年月 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS 売上累積
  FROM
    商品別月間売上
  GROUP BY
    商品
    , 売上年月
    , 売上高

実行結果①

image.png

コーディング例②

  SELECT
    A.商品
    , FORMAT(A.売上年月, 'yyyy年MM月') AS 売上年月
    , A.売上高
    , SUM(B.売上高) AS 売上累積
  FROM
    商品別月間売上 A
    INNER JOIN 商品別月間売上 B
        ON A.商品 = B.商品 AND A.売上年月 >= B.売上年月
  GROUP BY A.商品, A.売上年月, A.売上高
  ORDER BY A.商品, A.売上年月

実行結果②

image.png

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?