Skip to content

Instantly share code, notes, and snippets.

@voluntas
Created March 15, 2020 08:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voluntas/9846871193f1f44d0683627138723fc1 to your computer and use it in GitHub Desktop.
Save voluntas/9846871193f1f44d0683627138723fc1 to your computer and use it in GitHub Desktop.
SQLite3 で JSON 拡張 コトハジメ

SQLite3 で JSON 拡張 コトハジメ

注意

  • SQL 素人が書いてます

テーブルとデータ

CREATE TABLE authn_log (
    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,

    json JSON NOT NULL,

    created_unixtime INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
    created_at TIMESTAMP NOT NULL DEFAULT (DATETIME('now'))
);
INSERT INTO authn_log(json) VALUES('{"github_id": 1, "abc": 10}');
INSERT INTO authn_log(json) VALUES('{"github_id": 1, "abc": 10}');
INSERT INTO authn_log(json) VALUES('{"github_id": 2, "abc": 1}');
INSERT INTO authn_log(json) VALUES('{"github_id": 3, "abc": 20}');
INSERT INTO authn_log(json) VALUES('{"github_id": 3, "abc": 20}');

実行例

json の github_id の値で group by して abc の値を合計する

SELECT json_extract(json, '$.github_id'), sum(json_extract(json, '$.abc')) FROM authn_log GROUP BY json_extract(json, '$.github_id');
sqlite> SELECT json_extract(json, '$.github_id'), sum(json_extract(json, '$.abc')) FROM authn_log GROUP BY json_extract(json, '$.github_id');
1|20
2|1
3|40

資料

以下は雰囲気を掴むために読むくらいで良い。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment