sql >> Databáze >  >> RDS >> PostgreSQL

Opakování ve výběrovém dotazu

Jsou pro vás pole dobrá? (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}

Ve verzi 9.2 je možné mít sadu objektů 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]}

V 9.3 s přidáním lateral , jeden objekt (Fiddle)

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]}}"

V 9.2 je také možné mít jeden objekt spletitějším způsobem pomocí poddotazů namísto lateral



  1. porovnejte hodnoty oddělené čárkami v sql

  2. Escapování SQL dotazů v Codeigniter

  3. Odstraňte prvních X řádků databáze

  4. Historie patových situací v Oracle?