2014-03-03 31 views
1

我想按照列中的值對值進行分組。 這是一個例子: enter image description herePostgresSQL分組

我想獲得的輸出:

{{-30,-50,20},{-20,30,60},{-30,NULL or other value, 20}} 

我設法到達:

SELECT array_agg("val") 
FROM my_table 
WHERE "t_id" = 1 
GROUP BY "m_id"; 

{{-30,-50,20},{-20,30,60},{-30,20}} 

什麼是最好的辦法?

+0

也許加入合成表,以確保 「預期」 行。 – user2864740

回答

0
create table my_table (
    t_id int, 
    m_id int, 
    s_id int, 
    val int 
); 
insert into my_table (t_id, m_id, s_id, val) values 
(1,1,1,-30), 
(1,1,2,-50), 
(1,1,3,20), 
(1,2,1,-20), 
(1,2,2,30), 
(1,2,3,60), 
(1,3,1,-30), 
(1,3,3,20); 

select array_agg(val order by s_id) 
from 
    my_table t 
    right join 
    (
     (
      select distinct t_id, m_id 
      from my_table 
     ) a 
     cross join 
     (
      select distinct s_id 
      from my_table 
     ) b 
    ) s using (t_id, m_id, s_id) 
where t_id = 1 
group by m_id 
order by m_id 
; 
    array_agg 
--------------- 
{-30,-50,20} 
{-20,30,60} 
{-30,NULL,20}