sql >> データベース >  >> RDS >> PostgreSQL

選択クエリでループする

    アレイはあなたに適していますか? (SQL Fiddle)

    select
        id,
        sum(totalcol) as total,
        array_agg(somecol) as somecol,
        array_agg(totalcol) as totalcol
    from (
        select id, somecol, count(*) as totalcol
        from mytable
        group by id, somecol
    ) s
    group by id
    ;
     id | total | somecol | totalcol 
    ----+-------+---------+----------
      1 |     6 | {b,a,c} | {2,1,3}
      2 |     5 | {d,f}   | {2,3}
    

    9.2では、JSONオブジェクトのセットを(Fiddle) にすることができます。

    select row_to_json(s)
    from (
        select
            id,
            sum(totalcol) as total,
            array_agg(somecol) as somecol,
            array_agg(totalcol) as totalcol
        from (
            select id, somecol, count(*) as totalcol
            from mytable
            group by id, somecol
        ) s
        group by id
    ) s
    ;
                              row_to_json                          
    ---------------------------------------------------------------
     {"id":1,"total":6,"somecol":["b","a","c"],"totalcol":[2,1,3]}
     {"id":2,"total":5,"somecol":["d","f"],"totalcol":[2,3]}
    

    9.3では、lateralが追加されました 、単一のオブジェクト(フィドル)

    select to_json(format('{%s}', (string_agg(j, ','))))
    from (
        select format('%s:%s', to_json(id), to_json(c)) as j
        from
            (
                select
                    id,
                    sum(totalcol) as total_sum,
                    array_agg(somecol) as somecol_array,
                    array_agg(totalcol) as totalcol_array
                from (
                    select id, somecol, count(*) as totalcol
                    from mytable
                    group by id, somecol
                ) s
                group by id
            ) s
            cross join lateral
            (
                select
                    total_sum as total,
                    somecol_array as somecol,
                    totalcol_array as totalcol
            ) c
    ) s
    ;
                                                                    to_json                                                                
    ---------------------------------------------------------------------------------------------------------------------------------------
     "{1:{\"total\":6,\"somecol\":[\"b\",\"a\",\"c\"],\"totalcol\":[2,1,3]},2:{\"total\":5,\"somecol\":[\"d\",\"f\"],\"totalcol\":[2,3]}}"
    

    9.2では、lateralの代わりにサブクエリを使用して、より複雑な方法で単一のオブジェクトを作成することもできます。



    1. Oracle 9iが空の文字列をNULLとして扱うのはなぜですか?

    2. PHP-MySQLでのSELECTのパラメータ値のコーディング

    3. カウントのMYSQLカウント?

    4. MySQLからIDを選択し、開始IDと終了IDを除外します