Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@tamanobi

BigQueryで累積値を求める

More than 1 year has passed since last update.

Window関数 を使う。

データ

日付 アイテム 売上
2020-02-18 COMPグミ 100
2020-02-19 COMPグミ 100
2020-02-19 COMPグミ 100

上記データから特定の日付までの累積売上を求める

理想

日付 売上 累積売上
2020-02-18 100 100
2020-02-19 100 200
2020-02-19 100 300

SQL


#standardSQL
WITH SAMPLE_DATA AS(
SELECT * FROM UNNEST(ARRAY<STRUCT<time TIMESTAMP, item STRING, sales INT64>>
[
  ("2020-02-18 00:00:00+00", "COMPグミ", 100)
  , ("2020-02-19 00:00:00+00", "COMPグミ", 100)
  , ("2020-02-20 00:00:00+00", "COMPグミ", 100)
])
)

SELECT DATE(time) AS date
, sales
, SUM(sales) OVER (ORDER BY time ASC) AS sales_running
FROM SAMPLE_DATA

結果

日付 売上 累積売上
2020-02-18 100 100
2020-02-19 100 200
2020-02-19 100 300

解説

  • SUM() で合計するカラムを指定する
  • OVER() でどういうまとまりで、どういう順序で計算するか指定する
    • ここでは、 ORDER BY time ASC で順番しか指定していない
    • ここではやっていないが、 PARTITION BY を用いるとまとまりを指定できる

参考資料

0
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
tamanobi
Vim/Python/C++/Common Lisp/PHP/JavaScript/データ分析/機械学習/画像解析/NEM
admin-guild
「Webサービスの運営に必要なあらゆる知見」を共有できる場として作られた、運営者のためのコミュニティです。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?