Skip to content

Instantly share code, notes, and snippets.

@yancya
Created November 9, 2017 06:34
Show Gist options
  • Save yancya/2dd62c3822fbb29e7a2639a468bf5c7a to your computer and use it in GitHub Desktop.
Save yancya/2dd62c3822fbb29e7a2639a468bf5c7a to your computer and use it in GitHub Desktop.

データ

  WITH "user" AS (VALUES(1, 'taro'), (2, 'jiro'))
SELECT JSON_AGG("user")
  FROM "user";
             json_agg
-----------------------------------
 [{"column1":1,"column2":"taro"}, +
  {"column1":2,"column2":"jiro"}]
(1 row)

型定義

CREATE TYPE "user" AS (id integer, name text);
  WITH "user" AS (VALUES(1, 'taro'), (2, 'jiro'))
SELECT JSON_AGG("user"::"user") -- タプルの型が同じなので "user" 型にキャストできる
  FROM "user";
         json_agg
---------------------------
 [{"id":1,"name":"taro"}, +
  {"id":2,"name":"jiro"}]
(1 row)

テーブル定義

CREATE TABLE "user" (id integer, name text);
  WITH "user" AS (VALUES(1, 'taro'), (2, 'jiro'))
SELECT JSON_AGG("user"::"user") -- タプルの型が同じなので "user" 型にキャストできる
  FROM "user";
         json_agg
---------------------------
 [{"id":1,"name":"taro"}, +
  {"id":2,"name":"jiro"}]
(1 row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment