私のテーブルには次のデータがあります。
2016-01-01 : 1
2016-01-02 : 0
2016-01-03 : 4
2016-01-04 : 1
2016-01-05 : 2
次のようなレポート(線形成長)を生成したいと思います。
date : linear growth
2016-01-01 : 1
2016-01-02 : 1
2016-01-03 : 5
2016-01-04 : 6
2016-01-05 : 8
これを行うためのSQLステートメントの良いアイデアはありますか?
MySQLはSUM(...) OVER(...)
などのウィンドウ関数をサポートしていませんが、変数、自己結合、またはサブクエリを使用して計算できます。
SELECT created, value
, @growth := @growth + value as growth
FROM data
, (SELECT @growth := 0 as growth) as v
ORDER BY created
| created | value | growth |
|---------------------------|-------|--------|
| January, 01 2016 00:00:00 | 1 | 1 |
| January, 02 2016 00:00:00 | 0 | 1 |
| January, 03 2016 00:00:00 | 4 | 5 |
| January, 04 2016 00:00:00 | 1 | 6 |
| January, 05 2016 00:00:00 | 2 | 8 |
これは、self JOIN
を使用して実行することもできます。
SELECT d1.created, d1.value
, SUM(d2.value) as growth
FROM data d1
INNER JOIN data d2
ON d1.created >= d2.created
GROUP BY d1.created, d1.value
ORDER BY d1.created;
またはサブクエリを使用:
SELECT d1.created, d1.value
, (
SELECT SUM(value)
FROM data
WHERE created <= d1.created
) as growth
FROM mydata d1
ORDER BY d1.created;
複数のIDの増加を計算する場合は、追加の@id
変数とCASE
ステートメントを追加できます。
SELECT created, value
, CASE WHEN @id <> d.id THEN @growth := value
ELSE @growth := @growth + value
END as growth
, @id := d.id as id
FROM data d
, (SELECT @growth := 0 as growth, @id := 0 as id) as v
ORDER BY d.id, d.created;
SELECT d1.created, d1.value
, SUM(d2.value) as growth
, d1.id
FROM data d1
INNER JOIN data d2
ON d1.created >= d2.created AND d1.id = d2.id
GROUP BY d1.created, d1.value, d1.id
ORDER BY d1.created;
SELECT d1.id, d1.created, d1.value
, (
SELECT SUM(value)
FROM data
WHERE created <= d1.created AND id = d1.id
) as growth
FROM data d1
ORDER BY d1.id, d1.created;